From ad174d7356f37a96b4de5fd4590fe438a9e58ec8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=85=89=E6=98=A5?= Date: Sat, 12 Jun 2021 15:49:11 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E8=8E=B7=E5=8F=96=E5=AE=A2?= =?UTF-8?q?=E6=88=B7=E7=AB=AF=20IP?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- helper/request/request.go | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/helper/request/request.go b/helper/request/request.go index aa96166..c449413 100644 --- a/helper/request/request.go +++ b/helper/request/request.go @@ -1,6 +1,7 @@ package request import ( + "fmt" "math/rand" "net" "net/http" @@ -10,17 +11,33 @@ import ( // ClientIp 尽最大努力实现获取客户端 IP 的算法。 // 解析 X-Real-IP 和 X-Forwarded-For 以便于反向代理(nginx 或 haproxy)可以正常工作。 func ClientIp(r *http.Request) string { + // xForwardedFor xForwardedFor := r.Header.Get("X-Forwarded-For") + fmt.Printf("xForwardedFor:%v \n", xForwardedFor) ip := strings.TrimSpace(strings.Split(xForwardedFor, ",")[0]) if ip != "" { return ip } - + // xRealIp ip = strings.TrimSpace(r.Header.Get("X-Real-Ip")) if ip != "" { return ip } - + // HTTPCLIENTIP + HTTPCLIENTIP := r.Header.Get("HTTP_CLIENT_IP") + fmt.Printf("HTTPCLIENTIP:%v \n", HTTPCLIENTIP) + ip = strings.TrimSpace(strings.Split(HTTPCLIENTIP, ",")[0]) + if ip != "" { + return ip + } + // HTTPXFORWARDEDFOR + HTTPXFORWARDEDFOR := r.Header.Get("HTTP_X_FORWARDED_FOR") + fmt.Printf("HTTPXFORWARDEDFOR:%v \n", HTTPXFORWARDEDFOR) + ip = strings.TrimSpace(strings.Split(HTTPXFORWARDEDFOR, ",")[0]) + if ip != "" { + return ip + } + // system if ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)); err == nil { return ip } -- GitLab