From 3b39f0883c60b6978c6c6df2c0029bd4c96613fe Mon Sep 17 00:00:00 2001 From: Frédéric Guillot Date: Fri, 1 Jun 2018 07:22:18 -0700 Subject: Rewrite RealIP() to avoid returning an empty string --- http/request/request.go | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) (limited to 'http/request/request.go') diff --git a/http/request/request.go b/http/request/request.go index da79a3ff..1de6f736 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 +} -- cgit v1.2.3