27

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

 5 years ago
source link: https://studygolang.com/articles/15988?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK