go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/web/get_remoteaddr.go (about) 1 /* 2 3 Copyright (c) 2023 - Present. Will Charczuk. All rights reserved. 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository. 5 6 */ 7 8 package web 9 10 import ( 11 "net" 12 "net/http" 13 ) 14 15 // GetRemoteAddr gets the origin/client ip for a request. 16 // X-FORWARDED-FOR is checked. If multiple IPs are included the first one is returned 17 // X-REAL-IP is checked. If multiple IPs are included the last one is returned 18 // Finally r.RemoteAddr is used 19 // Only benevolent services will allow access to the real IP. 20 func GetRemoteAddr(r *http.Request) string { 21 if r == nil { 22 return "" 23 } 24 tryHeader := func(key string) (string, bool) { 25 return HeaderLastValue(r.Header, key) 26 } 27 for _, header := range []string{HeaderXForwardedFor, HeaderXRealIP} { 28 if headerVal, ok := tryHeader(header); ok { 29 return headerVal 30 } 31 } 32 ip, _, _ := net.SplitHostPort(r.RemoteAddr) 33 return ip 34 }