nginx反向代理下,golang程序获取用户真实IP

栏目: Go · 发布时间: 7年前

内容简介:在生产环境中我主要使用了beego和gin,下面只介绍这两个框架的情况。

nginx反向代理下,golang程序获取用户真实IP

在生产环境中我主要使用了beego和gin,下面只介绍这两个框架的情况。

Nginx的配置:

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;
}

项目中获取IP的代码:

  • 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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

Remote

Remote

Jason Fried、David Heinemeier Hansson / Crown Business / 2013-10-29 / CAD 26.95

The “work from home” phenomenon is thoroughly explored in this illuminating new book from bestselling 37signals founders Fried and Hansson, who point to the surging trend of employees working from hom......一起来看看 《Remote》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具