mirror of
https://github.com/gin-gonic/gin.git
synced 2025-10-16 05:16:35 +08:00
Use X-Forwarded-For before X-Real-Ip
Nginx uses X-Real-Ip with its IP instead of the client's IP. Therefore, we should use X-Forwarded-For *before* X-Real-Ip
This commit is contained in:
parent
f931d1ea80
commit
0d10500918
11
context.go
11
context.go
@ -305,13 +305,10 @@ func (c *Context) BindWith(obj interface{}, b binding.Binding) error {
|
|||||||
|
|
||||||
// ClientIP implements a best effort algorithm to return the real client IP, it parses
|
// ClientIP implements a best effort algorithm to return the real client IP, it parses
|
||||||
// X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy.
|
// X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy.
|
||||||
|
// Use X-Forwarded-For before X-Real-Ip as nginx uses X-Real-Ip with the proxy's IP.
|
||||||
func (c *Context) ClientIP() string {
|
func (c *Context) ClientIP() string {
|
||||||
if c.engine.ForwardedByClientIP {
|
if c.engine.ForwardedByClientIP {
|
||||||
clientIP := strings.TrimSpace(c.requestHeader("X-Real-Ip"))
|
clientIP := c.requestHeader("X-Forwarded-For")
|
||||||
if len(clientIP) > 0 {
|
|
||||||
return clientIP
|
|
||||||
}
|
|
||||||
clientIP = c.requestHeader("X-Forwarded-For")
|
|
||||||
if index := strings.IndexByte(clientIP, ','); index >= 0 {
|
if index := strings.IndexByte(clientIP, ','); index >= 0 {
|
||||||
clientIP = clientIP[0:index]
|
clientIP = clientIP[0:index]
|
||||||
}
|
}
|
||||||
@ -319,6 +316,10 @@ func (c *Context) ClientIP() string {
|
|||||||
if len(clientIP) > 0 {
|
if len(clientIP) > 0 {
|
||||||
return clientIP
|
return clientIP
|
||||||
}
|
}
|
||||||
|
clientIP = strings.TrimSpace(c.requestHeader("X-Real-Ip"))
|
||||||
|
if len(clientIP) > 0 {
|
||||||
|
return clientIP
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr)); err == nil {
|
if ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr)); err == nil {
|
||||||
return ip
|
return ip
|
||||||
|
Loading…
x
Reference in New Issue
Block a user