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.RemoteAddrc.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

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

查看所有标签

猜你喜欢:

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

The Sovereign Individual

The Sovereign Individual

James Dale Davidson、William Rees-Mogg / Free Press / 1999-08-26 / USD 16.00

Two renowned investment advisors and authors of the bestseller The Great Reckoning bring to light both currents of disaster and the potential for prosperity and renewal in the face of radical changes ......一起来看看 《The Sovereign Individual》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

在线进制转换器
在线进制转换器

各进制数互转换器