Skip to content

Instantly share code, notes, and snippets.

@thuydao
Created January 25, 2021 09:09
Show Gist options
  • Save thuydao/e94111dfa48e4c0a539c7529820b160e to your computer and use it in GitHub Desktop.
Save thuydao/e94111dfa48e4c0a539c7529820b160e to your computer and use it in GitHub Desktop.
go_remote_ip
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