// Package libstring provides various string related functions. package libstring import ( "net/http" "strings" ) // StringInSlice finds needle in a slice of strings. func StringInSlice(sliceString []string, needle string) bool { for _, b := range sliceString { if b == needle { return true } } return false } func ipAddrFromRemoteAddr(s string) string { idx := strings.LastIndex(s, ":") if idx == -1 { return s } return s[:idx] } // RemoteIP finds IP Address given http.Request struct. func RemoteIP(ipLookups []string, r *http.Request) string { realIP := r.Header.Get("X-Real-IP") forwardedFor := r.Header.Get("X-Forwarded-For") for _, lookup := range ipLookups { if lookup == "RemoteAddr" { return ipAddrFromRemoteAddr(r.RemoteAddr) } if lookup == "X-Forwarded-For" && forwardedFor != "" { // X-Forwarded-For is potentially a list of addresses separated with "," parts := strings.Split(forwardedFor, ",") for i, p := range parts { parts[i] = strings.TrimSpace(p) } return parts[0] } if lookup == "X-Real-IP" && realIP != "" { return realIP } } return "" }