修复CDN环境下获取真实客户端IP的问题

This commit is contained in:
2026-06-24 11:18:56 +08:00
parent fe69a2e38b
commit 1fc933e014
3 changed files with 19 additions and 2 deletions
+17
View File
@@ -1,6 +1,8 @@
package handlers
import (
"strings"
"github.com/gin-gonic/gin"
)
@@ -64,3 +66,18 @@ func getTr(c *gin.Context) map[string]string {
}
return m
}
// GetClientIP extracts the real client IP address, accounting for CDN/reverse proxy setups.
// It checks X-Forwarded-For and X-Real-IP headers before falling back to c.ClientIP().
func GetClientIP(c *gin.Context) string {
if xff := c.GetHeader("X-Forwarded-For"); xff != "" {
if i := strings.IndexByte(xff, ','); i != -1 {
return strings.TrimSpace(xff[:i])
}
return strings.TrimSpace(xff)
}
if xri := c.GetHeader("X-Real-IP"); xri != "" {
return strings.TrimSpace(xri)
}
return c.ClientIP()
}