Created
May 15, 2019 20:39
-
-
Save lfaoro/95d1923b5766b5b0948b8e4d38dd42fb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// From return client's real public IP address from http request headers. | |
func From(r *http.Request) string { | |
// Fetch header value | |
xRealIP := r.Header.Get("X-Real-IP") | |
xForwardedFor := r.Header.Get("X-Forwarded-For") | |
// If both empty, return IP from remote address | |
if xRealIP == "" && xForwardedFor == "" { | |
var remoteIP string | |
// If there are colon in remote address, remove the port number | |
// otherwise, return remote address as is | |
if strings.ContainsRune(r.RemoteAddr, ':') { | |
remoteIP, _, _ = net.SplitHostPort(r.RemoteAddr) | |
} else { | |
remoteIP = r.RemoteAddr | |
} | |
return remoteIP | |
} | |
// Check list of IP in X-Forwarded-For and return the first global address | |
for _, address := range strings.Split(xForwardedFor, ",") { | |
address = strings.TrimSpace(address) | |
isPrivate, err := isPrivateAddress(address) | |
if !isPrivate && err == nil { | |
return address | |
} | |
} | |
// If nothing succeed, return X-Real-IP | |
return xRealIP | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment