从服务器中的请求获取真实IP

Get real IP from Request in server

我正在尝试从 HTTP 请求中提取真实 IP。当我从部署在同一 VM 上的容器进行 CURL 调用时,我通过 r.RemoteAddr.

从 http 请求而不是 VM 的 IP 获取容器的 IP

但是当我使用 fmt.Printf("Request: %s", r) 打印请求时,我可以看到 VM 的真实 IP 在那里。来自 Print 语句的示例请求如下所示:

&{GET /containers/json HTTP/1.1 %!s(int=1) %!s(int=1) map[Accept:[*/*] User-Agent:[curl/7.64.0]] {} %!s(func() (io.ReadCloser, error)=<nil>) %!s(int64=0) [] %!s(bool=false) 10.32.20.122:2375 map[] map[] %!s(*multipart.Form=<nil>) map[] 172.20.0.1:47102 /containers/json %!s(*tls.ConnectionState=<nil>) %!s(<-chan struct {}=<nil>) %!s(*http.Response=<nil>) %!s(*context.cancelCtx=&{0xc000120480 {0 0} <nil> map[] <nil>})}

在上面的输出中,10.32.20.122 是 VM IP,172.20.0.1 是 docker 网络网关 IP。我要提取虚拟机IP。

你最好在 Printf

中使用 %+v
fmt.Printf("Request: %+v", r)

然后就可以看到这个字段叫什么了