Skip to content

Commit e82128f

Browse files
committed
refactor🎨: 优化获取客户端 IP 的逻辑,增加对 X-Forwarded-For 和 X-Real-IP 的处理
1 parent 8f8a197 commit e82128f

File tree

1 file changed

+11
-10
lines changed

1 file changed

+11
-10
lines changed

common/ip.go

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,23 @@ import (
66
)
77

88
func 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
}

0 commit comments

Comments
 (0)