You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

35 lines
544 B

package util
import (
"errors"
"net"
"net/http"
"strings"
)
// GetIP returns request real ip.
func GetIP(r *http.Request) (string, error) {
ip := r.Header.Get("X-Real-IP")
if net.ParseIP(ip) != nil {
return ip, nil
}
ip = r.Header.Get("X-Forward-For")
for _, i := range strings.Split(ip, ",") {
if net.ParseIP(i) != nil {
return i, nil
}
}
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return "", err
}
if net.ParseIP(ip) != nil {
return ip, nil
}
return "", errors.New("no valid ip found")
}