fusenapi/utils/ip/remote_addr.go
laodaming c17ab5ae5c fix
2023-06-30 17:20:11 +08:00

26 lines
493 B
Go

package ip
import (
"net"
"net/http"
"strings"
)
// 获取客户端ip地址
func GetClientIP(r *http.Request) (ip string, err error) {
xForwardedFor := r.Header.Get("X-Forwarded-For")
ip = strings.TrimSpace(strings.Split(xForwardedFor, ",")[0])
if ip != "" {
return ip, nil
}
ip = strings.TrimSpace(r.Header.Get("X-Real-Ip"))
if ip != "" {
return ip, nil
}
ip, _, err = net.SplitHostPort(strings.TrimSpace(r.RemoteAddr))
if err != nil {
return "", err
}
return ip, nil
}