Преглед на файлове

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
tsirolnik преди 9 години
родител
ревизия
c115074d77
променени са 1 файла, в които са добавени 6 реда и са изтрити 5 реда
  1. 6 5
      context.go

+ 6 - 5
context.go

@@ -349,13 +349,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
 // 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 {
 	if c.engine.ForwardedByClientIP {
-		clientIP := strings.TrimSpace(c.requestHeader("X-Real-Ip"))
-		if len(clientIP) > 0 {
-			return clientIP
-		}
-		clientIP = c.requestHeader("X-Forwarded-For")
+		clientIP := c.requestHeader("X-Forwarded-For")
 		if index := strings.IndexByte(clientIP, ','); index >= 0 {
 			clientIP = clientIP[0:index]
 		}
@@ -363,6 +360,10 @@ func (c *Context) ClientIP() string {
 		if len(clientIP) > 0 {
 			return clientIP
 		}
+		clientIP = strings.TrimSpace(c.requestHeader("X-Real-Ip"))
+		if len(clientIP) > 0 {
+			return clientIP
+		}
 	}
 
 	if c.engine.AppEngine {