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

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

查看所有标签

猜你喜欢:

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

Django 1.0 Template Development

Django 1.0 Template Development

Scott Newman / Packt / 2008 / 24.99

Django is a high-level Python web application framework designed to support the rapid development of dynamic websites, web applications, and web services. Getting the most out of its template system a......一起来看看 《Django 1.0 Template Development》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具