26 lines
493 B
Go
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
|
|
}
|