diff options
Diffstat (limited to 'http/request/request.go')
-rw-r--r-- | http/request/request.go | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/http/request/request.go b/http/request/request.go index da79a3f..1de6f73 100644 --- a/http/request/request.go +++ b/http/request/request.go @@ -6,8 +6,10 @@ package request import ( "fmt" + "net" "net/http" "strconv" + "strings" "github.com/gorilla/mux" ) @@ -88,3 +90,30 @@ func HasQueryParam(r *http.Request, param string) bool { _, ok := values[param] return ok } + +// RealIP returns client's real IP address. +func RealIP(r *http.Request) string { + headers := []string{"X-Forwarded-For", "X-Real-Ip"} + for _, header := range headers { + value := r.Header.Get(header) + + if value != "" { + addresses := strings.Split(value, ",") + address := strings.TrimSpace(addresses[0]) + + if net.ParseIP(address) != nil { + return address + } + } + } + + // Fallback to TCP/IP source IP address. + var remoteIP string + if strings.ContainsRune(r.RemoteAddr, ':') { + remoteIP, _, _ = net.SplitHostPort(r.RemoteAddr) + } else { + remoteIP = r.RemoteAddr + } + + return remoteIP +} |