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.
goip/vendor/github.com/dtapps/gorequest/ip.go

49 lines
1006 B

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package gorequest
import (
"net"
"net/http"
"strings"
)
const Version = "1.0.1"
// ClientIp 尽最大努力实现获取客户端 IP 的算法。
// 解析 X-Real-IP 和 X-Forwarded-For 以便于反向代理nginx 或 haproxy可以正常工作。
func ClientIp(r *http.Request) string {
// 转发IP
xForwardedFor := r.Header.Get("X-Forwarded-For")
ip := strings.TrimSpace(strings.Split(xForwardedFor, ",")[0])
if ip != "" {
return ip
}
// 真实Ip
ip = strings.TrimSpace(r.Header.Get("X-Real-Ip"))
if ip != "" {
return ip
}
// HTTP客户端IP
httpClientIp := r.Header.Get("HTTP_CLIENT_IP")
ip = strings.TrimSpace(strings.Split(httpClientIp, ",")[0])
if ip != "" {
return ip
}
// HTTP转发IP
HttpXForwardedFor := r.Header.Get("HTTP_X_FORWARDED_FOR")
ip = strings.TrimSpace(strings.Split(HttpXForwardedFor, ",")[0])
if ip != "" {
return ip
}
// 系统
if ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)); err == nil {
return ip
}
return ""
}