Created
January 25, 2021 09:09
-
-
Save thuydao/e94111dfa48e4c0a539c7529820b160e to your computer and use it in GitHub Desktop.
go_remote_ip
This file contains hidden or 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
func _ip(r *http.Request) string { | |
//Get IP from the X-REAL-IP header | |
ip := r.Header.Get("X-REAL-IP") | |
netIP := net.ParseIP(ip) | |
if netIP != nil { | |
return ip | |
} | |
//Get IP from X-FORWARDED-FOR header | |
ips := r.Header.Get("X-FORWARDED-FOR") | |
splitIps := strings.Split(ips, ",") | |
for _, ip := range splitIps { | |
netIP := net.ParseIP(ip) | |
if netIP != nil { | |
return ip | |
} | |
} | |
//Get IP from RemoteAddr | |
ip, _, err := net.SplitHostPort(r.RemoteAddr) | |
if err != nil { | |
return "" | |
} | |
netIP = net.ParseIP(ip) | |
if netIP != nil { | |
return ip | |
} | |
return "" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment