github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/httptransport/httpx/util.go (about) 1 package httpx 2 3 import ( 4 "net" 5 "net/http" 6 "strings" 7 ) 8 9 func ClientIP(r *http.Request) string { 10 clientIP := ClientIPByHeaderForwardedFor(r.Header.Get(HeaderForwardedFor)) 11 if clientIP != "" { 12 return clientIP 13 } 14 15 clientIP = ClientIPByHeaderRealIP(r.Header.Get(HeaderRealIP)) 16 if clientIP != "" { 17 return clientIP 18 } 19 20 if ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)); err == nil { 21 return ip 22 } 23 24 return "" 25 } 26 27 // ClientIPByHeaderForwardedFor 28 // X-Forwarded-For: client, proxy1, proxy2 29 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For 30 func ClientIPByHeaderForwardedFor(headerForwardedFor string) string { 31 if index := strings.IndexByte(headerForwardedFor, ','); index >= 0 { 32 return headerForwardedFor[0:index] 33 } 34 return strings.TrimSpace(headerForwardedFor) 35 } 36 37 // ClientIPByHeaderRealIP 38 // X-Forwarded-For: client, proxy1, proxy2 39 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For 40 func ClientIPByHeaderRealIP(headerRealIP string) string { 41 return strings.TrimSpace(headerRealIP) 42 }