3 回答

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超7個(gè)贊
查看http.Request您可以找到以下成員變量:
// HTTP defines that header names are case-insensitive.
// The request parser implements this by canonicalizing the
// name, making the first character and any characters
// following a hyphen uppercase and the rest lowercase.
//
// For client requests certain headers are automatically
// added and may override values in Header.
//
// See the documentation for the Request.Write method.
Header Header
// RemoteAddr allows HTTP servers and other software to record
// the network address that sent the request, usually for
// logging. This field is not filled in by ReadRequest and
// has no defined format. The HTTP server in this package
// sets RemoteAddr to an "IP:port" address before invoking a
// handler.
// This field is ignored by the HTTP client.
RemoteAddr string
您可以使用RemoteAddr獲取遠(yuǎn)程客戶端的 IP 地址和端口(格式為“IP:port”),這是原始請(qǐng)求者或最后一個(gè)代理(例如位于您的服務(wù)器前面的負(fù)載均衡器)的地址。
這就是你所擁有的一切。
然后您可以調(diào)查不區(qū)分大小寫(xiě)的標(biāo)題(根據(jù)上面的文檔),這意味著您的所有示例都將工作并產(chǎn)生相同的結(jié)果:
req.Header.Get("X-Forwarded-For") // capitalisation
req.Header.Get("x-forwarded-for") // doesn't
req.Header.Get("X-FORWARDED-FOR") // matter
這是因?yàn)閮?nèi)部http.Header.Get會(huì)為您規(guī)范密鑰。(如果您想直接訪問(wèn)標(biāo)頭映射,而不是通過(guò)Get,則需要先使用http.CanonicalHeaderKey。)
最后,"X-Forwarded-For"可能是您想要查看的字段,以便獲取有關(guān)客戶端 IP 的更多信息。這在很大程度上取決于遠(yuǎn)程端使用的 HTTP 軟件,因?yàn)榭蛻舳丝梢愿鶕?jù)需要在其中放置任何內(nèi)容。另請(qǐng)注意,此字段的預(yù)期格式是逗號(hào)+空格分隔的 IP 地址列表。您需要稍微解析一下以獲得您選擇的單個(gè) IP(可能是列表中的第一個(gè) IP),例如:
// Assuming format is as expected
ips := strings.Split("10.0.0.1, 10.0.0.2, 10.0.0.3", ", ")
for _, ip := range ips {
fmt.Println(ip)
}
將產(chǎn)生:
10.0.0.1
10.0.0.2
10.0.0.3

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超2個(gè)贊
這就是我想出IP的方式
func ReadUserIP(r *http.Request) string {
IPAddress := r.Header.Get("X-Real-Ip")
if IPAddress == "" {
IPAddress = r.Header.Get("X-Forwarded-For")
}
if IPAddress == "" {
IPAddress = r.RemoteAddr
}
return IPAddress
}
X-Real-Ip - 獲取第一個(gè)真實(shí) IP(如果請(qǐng)求位于多個(gè) NAT 源/負(fù)載均衡器后面)
X-Forwarded-For - 如果由于某種原因 X-Real-Ip 為空白且不返回響應(yīng),則從 X-Forwarded-For 獲取
遠(yuǎn)程地址 - 最后的手段(通常不可靠,因?yàn)檫@可能是最后一個(gè) ip 或者如果它是對(duì)服務(wù)器的裸 http 請(qǐng)求,即沒(méi)有負(fù)載平衡器)
- 3 回答
- 0 關(guān)注
- 542 瀏覽
添加回答
舉報(bào)