From 1fc933e014959bba26382ad55e754066029a1b88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=97=A0=E9=97=BB=E9=A3=8E?= Date: Wed, 24 Jun 2026 11:18:56 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8DCDN=E7=8E=AF=E5=A2=83?= =?UTF-8?q?=E4=B8=8B=E8=8E=B7=E5=8F=96=E7=9C=9F=E5=AE=9E=E5=AE=A2=E6=88=B7?= =?UTF-8?q?=E7=AB=AFIP=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- handlers/comment.go | 2 +- handlers/helpers.go | 17 +++++++++++++++++ handlers/home.go | 2 +- 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/handlers/comment.go b/handlers/comment.go index 1a8f63f..3ffdf02 100644 --- a/handlers/comment.go +++ b/handlers/comment.go @@ -183,7 +183,7 @@ func PostComment(db *gorm.DB) gin.HandlerFunc { Content: sanitizeMarkdown(form.Content), IsPrivate: form.IsPrivate, Status: models.CommentApproved, - IPAddress: truncate(c.ClientIP(), 64), + IPAddress: truncate(GetClientIP(c), 64), UserAgent: truncate(c.GetHeader("User-Agent"), 512), } diff --git a/handlers/helpers.go b/handlers/helpers.go index 8839dca..ed2c01d 100644 --- a/handlers/helpers.go +++ b/handlers/helpers.go @@ -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() +} diff --git a/handlers/home.go b/handlers/home.go index 06778f3..4253841 100644 --- a/handlers/home.go +++ b/handlers/home.go @@ -306,7 +306,7 @@ func recordArticleView(db *gorm.DB, articleID uint, c *gin.Context) { } // Get client IP and User-Agent - ip := c.ClientIP() + ip := GetClientIP(c) userAgent := c.Request.UserAgent() isBot := models.IsBot(userAgent)