github.com/craicoverflow/tyk@v2.9.6-rc3+incompatible/request/real_ip.go (about) 1 package request 2 3 import ( 4 "net" 5 "net/http" 6 "strings" 7 8 "github.com/TykTechnologies/tyk/headers" 9 ) 10 11 // RealIP takes a request object, and returns the real Client IP address. 12 func RealIP(r *http.Request) string { 13 14 if contextIp := r.Context().Value("remote_addr"); contextIp != nil { 15 return contextIp.(string) 16 } 17 18 if realIP := r.Header.Get(headers.XRealIP); realIP != "" { 19 return realIP 20 } 21 22 if fw := r.Header.Get(headers.XForwardFor); fw != "" { 23 // X-Forwarded-For has no port 24 if i := strings.IndexByte(fw, ','); i >= 0 { 25 26 return fw[:i] 27 } 28 29 return fw 30 } 31 32 // From net/http.Request.RemoteAddr: 33 // The HTTP server in this package sets RemoteAddr to an 34 // "IP:port" address before invoking a handler. 35 // So we can ignore the case of the port missing. 36 host, _, _ := net.SplitHostPort(r.RemoteAddr) 37 return host 38 }