简体   繁体   English

从Go HTTP Server获取源IP地址

[英]Get Source IP Address from Go HTTP Server

I am trying to implement a HTTP server in Golang that receives requests from an Amazon ELB that uses the proxy protocol. 我正在尝试在Golang中实现一个HTTP服务器,该服务器从使用代理协议的Amazon ELB接收请求。 Now I'd like to know what the original IP address is and so I was thinking about using this package. 现在,我想知道原始IP地址是什么,因此我正在考虑使用软件包。

Now this package talks raws HTTP as far as I can tell but my server implements a higher level HTTP server with a router. 现在,据我所知, 程序包使用的是原始HTTP,但是我的服务器使用路由器实现了更高级别的HTTP服务器。

I am having trouble translating between them. 我在他们之间进行翻译时遇到麻烦。 My question is this : how do I use this library and still use a router like gorilla/mux? 我的问题是我该如何使用库并且仍使用大猩猩/多路复用器之类的路由器? Now there's nothing special about this package, it just talks at a lower level than HTTP. 现在, 程序包没有什么特别的,它的讨论级别比HTTP低。

Example: 例:

// Listen on TCP port 2000 on all interfaces.
l, err := net.Listen("tcp", ":2000")
// proxyproxy is the library that maintains the source ip address for me
proxyList := &proxyproto.Listener{Listener: list}
if err != nil {
    log.Fatal(err)
}
defer proxyList.Close()

for {
    // Wait for a connection.
    conn, err := proxyList.Accept()
    if err != nil {
        log.Fatal(err)
    }
    // Handle the connection in a new goroutine.
    // The loop then returns to accepting, so that
    // multiple connections may be served concurrently.
    go func(c net.Conn) {

        // how do I connect my router

    }(conn)
}

The usual way of finding out the actual client IP over HTTP is by using some HTTP headers such as: 通过HTTP查找实际客户端IP的通常方法是使用一些HTTP标头,例如:

  • X-Forwarded-For
  • X-Real-IP

Actually, Amazon ELB seems to support the X-Forwarded-For header: 实际上,Amazon ELB似乎支持X-Forwarded-For标头:

http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html

If you are using Gorilla, they have a middleware that seems to take care of that for you: 如果您使用的是Gorilla,那么他们的中间件似乎可以帮助您解决该问题:

https://godoc.org/github.com/gorilla/handlers#ProxyHeaders https://godoc.org/github.com/gorilla/handlers#ProxyHeaders

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM