前言
如果你配置好了 nginx,而且確認了很多遍,但是gin就是獲取不到真實ip。如果還在搜解決辦法,到這裏你可以停止了:
這是gin1.7版本的 BUG
這是gin1.7版本的 BUG
這是gin1.7版本的 BUG
github討論地址:https://github.com/gin-gonic/gin/issues/2697
解決辦法:
不要用 c.ClientIP()
獲取ip, 使用:c.Request.Header.Get("X-Forwarded-For")
如果這個帖子對你有幫助,而且幫你省了很多時間,記得點擊博文末尾,請我喝杯咖啡哦
正文
nginx 配置
網上教配置nginx的教程一大堆,都大同小異,這是我的配置。
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Server $host;
proxy_buffers 16 16k;
proxy_buffer_size 16k;
proxy_pass http://127.0.0.1:3988/;
}
gin獲取真實ip
如果你的gin版本小於 1.7
// 獲取ip函數
func GetIp(c *gin.Context) string {
reqIP := c.ClientIP()
if reqIP == "::1" {
reqIP = "127.0.0.1"
}
return reqIP
}
如果你的gin版本大於等於1.7
// 獲取ip函數
func GetIp(c *gin.Context) string {
reqIP :=c.Request.Header.Get("X-Forwarded-For")
if reqIP == "::1" {
reqIP = "127.0.0.1"
}
return reqIP
}
結尾
記錄我遇到的問題,讓更多的人少早彎路,我是水車,一個想用代碼實現財務自由的程序員