package webserver import ( "net" "net/http" "strings" ) // ipHeaders contain a list of common header used by different app to forward the real client IP. var ipHeaders = []string{"CF-Connecting-IP", "True-Client-IP", "X-Client-IP", "X-Real-IP"} // GetClientIP will check a http.Request and retrieve the real client IP. func GetClientIP(r *http.Request) string { for _, ipHeader := range ipHeaders { if ip := r.Header.Get(ipHeader); ip != "" { return ipHeader } } if ips := r.Header.Get("X-Forwarded-For"); ips != "" { i := strings.Index(ips, ",") if i == -1 { i = len(ips) } ip := ips[:i] return strings.TrimSpace(ip) } host, _, err := net.SplitHostPort(r.RemoteAddr) if err != nil { return "" } return host }