github.com/searKing/golang/go@v1.2.117/net/http/request.go (about) 1 // Copyright 2021 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package http 6 7 import ( 8 "net/http" 9 "strings" 10 11 net_ "github.com/searKing/golang/go/net" 12 strings_ "github.com/searKing/golang/go/strings" 13 ) 14 15 // ClientIP implements a best effort algorithm to return the real client IP, it parses 16 // X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy. 17 // Use X-Forwarded-For before X-Real-Ip as nginx uses X-Real-Ip with the proxy's IP. 18 func ClientIP(req *http.Request) string { 19 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For 20 // https://cloud.google.com/appengine/docs/flexible/python/reference/request-headers 21 clientIP := strings_.ValueOrDefault( 22 strings.TrimSpace(strings.Split(req.Header.Get("X-Forwarded-For"), ",")[0]), 23 strings.TrimSpace(req.Header.Get("X-Real-Ip")), 24 strings.TrimSpace(req.Header.Get("X-Appengine-Remote-Addr"))) 25 if clientIP != "" { 26 return clientIP 27 } 28 29 if ip, _, err := net_.SplitHostPort(strings.TrimSpace(req.RemoteAddr)); err == nil { 30 return ip 31 } 32 33 return "" 34 }