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)