美文网首页golang
fasthttp 获取client ip

fasthttp 获取client ip

作者: 1行者 | 来源:发表于2017-12-28 16:49 被阅读164次

    用fasthttp 获取客户端ip 的方法是 ctx.RemoteIP().String(),正常情况下这个获取是没有问题的,但是如果使用了 nginx 等代理的时候这些就不准了,RemoteIP 获取的其实是nginx 的IP,那么如何解决呢?

      1. 首相要在nginx 里面加一些配置例如

    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

      1. 从 header 里面获取 client ip
    //获取真实的IP  1.1.1.1, 2.2.2.2, 3.3.3.3
    func ClientIP(ctx *fasthttp.RequestCtx) string {
        clientIP := string(ctx.Request.Header.Peek("X-Forwarded-For"))
        if index := strings.IndexByte(clientIP, ','); index >= 0 {
            clientIP = clientIP[0:index]
                    //获取最开始的一个 即 1.1.1.1
        }
        clientIP = strings.TrimSpace(clientIP)
        if len(clientIP) > 0 {
            return clientIP
        }
        clientIP = strings.TrimSpace(string(ctx.Request.Header.Peek("X-Real-Ip")))
        if len(clientIP) > 0 {
            return clientIP
        }
        return ctx.RemoteIP().String()
    }
    
    

    相关文章

      网友评论

        本文标题:fasthttp 获取client ip

        本文链接:https://www.haomeiwen.com/subject/hfevgxtx.html