github.com/prebid/prebid-server/v2@v2.18.0/util/httputil/httputil.go (about) 1 package httputil 2 3 import ( 4 "net" 5 "net/http" 6 "strings" 7 8 "github.com/prebid/prebid-server/v2/util/iputil" 9 ) 10 11 var ( 12 trueClientIP = http.CanonicalHeaderKey("True-Client-IP") 13 xForwardedFor = http.CanonicalHeaderKey("X-Forwarded-For") 14 xRealIP = http.CanonicalHeaderKey("X-Real-IP") 15 ) 16 17 type ContentEncoding string 18 19 const ( 20 ContentEncodingGZIP ContentEncoding = "gzip" 21 ) 22 23 func (k ContentEncoding) Normalize() ContentEncoding { 24 return ContentEncoding(strings.ToLower(string(k))) 25 } 26 27 // FindIP returns the first ip address found in the http request matching the predicate v. 28 func FindIP(r *http.Request, v iputil.IPValidator) (net.IP, iputil.IPVersion) { 29 if ip, ver := findTrueClientIP(r, v); ip != nil { 30 return ip, ver 31 } 32 33 if ip, ver := findForwardedFor(r, v); ip != nil { 34 return ip, ver 35 } 36 37 if ip, ver := findRealIP(r, v); ip != nil { 38 return ip, ver 39 } 40 41 if ip, ver := findRemoteAddr(r, v); ip != nil { 42 return ip, ver 43 } 44 45 return nil, iputil.IPvUnknown 46 } 47 48 func findTrueClientIP(r *http.Request, v iputil.IPValidator) (net.IP, iputil.IPVersion) { 49 if value := r.Header.Get(trueClientIP); value != "" { 50 value = strings.TrimSpace(value) 51 if ip, ver := iputil.ParseIP(value); ip != nil && v.IsValid(ip, ver) { 52 return ip, ver 53 } 54 } 55 return nil, iputil.IPvUnknown 56 } 57 58 func findForwardedFor(r *http.Request, v iputil.IPValidator) (net.IP, iputil.IPVersion) { 59 if value := r.Header.Get(xForwardedFor); value != "" { 60 for _, p := range strings.Split(value, ",") { 61 p = strings.TrimSpace(p) 62 if ip, ver := iputil.ParseIP(p); ip != nil && v.IsValid(ip, ver) { 63 return ip, ver 64 } 65 } 66 } 67 return nil, iputil.IPvUnknown 68 } 69 70 func findRealIP(r *http.Request, v iputil.IPValidator) (net.IP, iputil.IPVersion) { 71 if value := r.Header.Get(xRealIP); value != "" { 72 value = strings.TrimSpace(value) 73 if ip, ver := iputil.ParseIP(value); ip != nil && v.IsValid(ip, ver) { 74 return ip, ver 75 } 76 } 77 return nil, iputil.IPvUnknown 78 } 79 80 func findRemoteAddr(r *http.Request, v iputil.IPValidator) (net.IP, iputil.IPVersion) { 81 if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil { 82 if ip, ver := iputil.ParseIP(host); ip != nil && v.IsValid(ip, ver) { 83 return ip, ver 84 } 85 } 86 return nil, iputil.IPvUnknown 87 }