需要注意的一件事是 req.RemoteAddr 最终会得到应用程序链中最后一个代理的 IP 地址。在 App Engine 上,这可能最终会成为 127.0.0.1。net.SplitHostPort
可能会出错,因为 IP 实际上可能没有端口号。
Region、City 和 CityLatLong 数据将来自您的 IP,如果该信息可用,则可能不是因为它不是严格要求的。您可以尝试从 X-Forwarded-For 标头中提取 IP 地址。这通常会为您提供完整的代理列表和原始 IP 地址(IPv4 或 IPv6,请参见下面的示例结果)。
如果你要使用:package hello
import (
"fmt"
"net"
"net/http"
)
func init() {
http.HandleFunc("/", handler)
}
func handler(w http.ResponseWriter, r *http.Request) {
clientIPAddress, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
clientIPAddress = err.Error()
}
rAddr := r.RemoteAddr
forward := r.Header.Get("x-forwarded-for")
country := r.Header.Get("X-AppEngineCountry")
region := r.Header.Get("X-AppEngine-Region")
city := r.Header.Get("X-AppEngine-City")
cityLatLong := r.Header.Get("X-AppEngine-CityLatLong")
fullHeader := r.Header
fmt.Fprintf(w, "Hello, world!\n %v\n %v\n %v\n %v\n %v\n %v\n %v\n %v",
clientIPAddress,
rAddr,
forward,
country,
region,
city,
cityLatLong,
fullHeader
)
}
您应该会看到类似的内容(只要 Region City、CityLatLong 可用,否则将为空白):
Hello, world!
missing port in address 127.0.0.1
127.0.0.1
2601:1c2:600:17b0::::, 2607:f8b0:400a:::2014
ZZ
or
portland
45.523452,-122.676207
map[Accept-Encoding:[identity] X-Appengine-Default-Version-Hostname:
[127.0.0.1:8080] X-Appengine-User-Organization:[] X-Appengine-Citylatlong:
[45.523452,-122.676207] X-Appengine-Request-Log-Id:
[48f03baada92bbb3872a8b3a5baa3f8b0dfff413f64fbcfa] X-
Appengine-City:[portland] X-Forwarded-Proto:[https] X-Appengine-Server-Name:
[127.0.0.1] Via:[1.1 google] X-Appengine-Server-Software:[Development/2.0]
X-Appengine-User-Id:[] X-Forwarded-For:
[2601:1c2:600:17b0:::: 2607:f8b0:400a:::2014] X-Goog-
Cloud-Shell-Target-Host:[127.0.0.1] X-Appengine-Country:[ZZ] Accept:
etc
etc
希望有帮助。