社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
在生产环境中我主要使用了beego和gin,下面只介绍这两个框架的情况。
location /api {
proxy_set_header Host $http_host;
proxy_set_header X-Forward-For $remote_addr;
proxy_set_header X-real-ip $remote_addr;
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
proxy_pass http://127.0.0.1:9900;
}
gin:
gin框架提供的方法就能够获取准确的ip信息。
ip := c.ClientIP() // c为*gin.Context
beego:
尝试了c.Ctx.Request.RemoteAddr
和 c.Ctx.Input.IP()
两种方法后,都没有得到想要的结果,参考gin框架的方法,自己编写了下面的方法。 当然这个方法其实不依赖于某个具体框架了,只要框架中的能够获得原生的Request对像,这个方法也是适用的。
func getClientIP(ctx *context.Context) string {
ip := ctx.Request.Header.Get("X-Forwarded-For")
if strings.Contains(ip, "127.0.0.1") || ip == "" {
ip = ctx.Request.Header.Get("X-real-ip")
}
if ip == "" {
return "127.0.0.1"
}
return ip
}
// caller
ip := getClientIP(c.Ctx) // Ctx为beego包中的*context.Context
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!