获取远程ip地址时使用nginx代理Glang Gin?



我使用Nginx作为golang API应用程序的代理,该应用程序使用go gin框架
Nginx配置很简单

server {
listen 80;
listen [::]:80;
location / {
proxy_pass  http://127.0.0.1:3000;
proxy_set_header X-Client-IP $remote_addr;
proxy_set_header  X-Appengine-Remote-Addr $remote_addr;
add_header Access-Control-Allow-Origin *;
proxy_set_header   Upgrade          $http_upgrade;
proxy_set_header   Connection       upgrade;
proxy_set_header   Accept-Encoding  gzip;
}
}

和Go代码使用

将IP地址存储到数据库
ctx.RemoteIP()

获取IP问题是它总是存储127.0.0.1,从来没有得到真正请求的IP
我切换到另一个函数

ctx.ClientIP()

和同样的问题,它存储127.0.0.1而不是请求IP

在两种方法中,我都将可信代理设置为"x - client - ip">

func main() {
r := gin.Default()
r.TrustedPlatform = "X-Client-IP"
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pongy",
})
})
r.POST("/signup", controllers.SignUp)
r.POST("/login", controllers.Login)
r.GET("/validation", middleware.RequireAuth, controllers.Validation)
r.Run("127.0.0.1:3000") // listen and serve on 0.0.0.0:8080
}

我相信你想做两件事来解决这个问题。

首先,将标题名称从X-Client-IP更改为X-Real-IPX-Forwarded-For

然后,像这样设置localhost为可信代理:

r.SetTrustedProxies([]string{"127.0.0.1", "::1"})

用上面的代码替换r.TrustedPlatform = "X-Client-IP"行,调用ctx.ClientIP()应该返回你想要的内容。

您可以在Gin源代码中看到,它正在查找这两个头名称。

最新更新