File tree Expand file tree Collapse file tree 1 file changed +11
-10
lines changed
Expand file tree Collapse file tree 1 file changed +11
-10
lines changed Original file line number Diff line number Diff line change @@ -6,22 +6,23 @@ import (
66)
77
88func GetClientIP (c * gin.Context ) string {
9- ClientIP := c .ClientIP ()
10- //fmt.Println("ClientIP:", ClientIP)
11- RemoteIP := c .RemoteIP ()
12- //fmt.Println("RemoteIP:", RemoteIP)
9+ // 优先从 X-Forwarded-For 获取 IP
1310 ip := c .Request .Header .Get ("X-Forwarded-For" )
14- if strings .Contains (ip , "127.0.0.1" ) || ip == "" {
11+ if ip == "" || strings .Contains (ip , "127.0.0.1" ) {
12+ // 如果为空或为本地地址,则尝试从 X-Real-IP 获取
1513 ip = c .Request .Header .Get ("X-real-ip" )
1614 }
1715 if ip == "" {
18- ip = "127.0.0.1"
16+ // 如果仍为空,则使用 RemoteIP
17+ ip = c .RemoteIP ()
1918 }
20- if RemoteIP != "127.0.0.1" {
21- ip = RemoteIP
19+ if ip == "" || ip == "127.0.0.1" {
20+ // 如果仍为空或为本地地址,则使用 ClientIP
21+ ip = c .ClientIP ()
2222 }
23- if ClientIP != "127.0.0.1" {
24- ip = ClientIP
23+ if ip == "" {
24+ // 最后兜底为本地地址
25+ ip = "127.0.0.1"
2526 }
2627 return ip
2728}
You can’t perform that action at this time.
0 commit comments