修复CDN环境下获取真实客户端IP的问题
This commit is contained in:
+1
-1
@@ -183,7 +183,7 @@ func PostComment(db *gorm.DB) gin.HandlerFunc {
|
|||||||
Content: sanitizeMarkdown(form.Content),
|
Content: sanitizeMarkdown(form.Content),
|
||||||
IsPrivate: form.IsPrivate,
|
IsPrivate: form.IsPrivate,
|
||||||
Status: models.CommentApproved,
|
Status: models.CommentApproved,
|
||||||
IPAddress: truncate(c.ClientIP(), 64),
|
IPAddress: truncate(GetClientIP(c), 64),
|
||||||
UserAgent: truncate(c.GetHeader("User-Agent"), 512),
|
UserAgent: truncate(c.GetHeader("User-Agent"), 512),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
package handlers
|
package handlers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -64,3 +66,18 @@ func getTr(c *gin.Context) map[string]string {
|
|||||||
}
|
}
|
||||||
return m
|
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()
|
||||||
|
}
|
||||||
|
|||||||
+1
-1
@@ -306,7 +306,7 @@ func recordArticleView(db *gorm.DB, articleID uint, c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Get client IP and User-Agent
|
// Get client IP and User-Agent
|
||||||
ip := c.ClientIP()
|
ip := GetClientIP(c)
|
||||||
userAgent := c.Request.UserAgent()
|
userAgent := c.Request.UserAgent()
|
||||||
isBot := models.IsBot(userAgent)
|
isBot := models.IsBot(userAgent)
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user