英文:
How to get client ip address using gorilla/mux - GoLang
问题
我正在使用强大的gorilla/mux库在golang中实现一个API应用程序,该库有助于构建Web API。
然而,我需要为每个访问网站的客户端保留IP地址,那么如何获取每个客户端的IP地址呢?
代码:
func GetIpAddress(w http.ResponseWriter, r *http.Request){
// 每当用户访问此URL(此函数)
// 我们需要知道用户的IP地址
output := r.UserAgent()
fmt.Print("Output : ", output)
// 但是变量(output)返回的是不包括客户端IP地址的整个字符串
}
英文:
I am implementing an API application in golang using gorilla/mux which is a powerfull library, tends to help to build web APIs,
However i need to keep ip address for each client for that how can i get ip address for each client who visits website?
Code:
func GetIpAddress(w http.ResponseWriter, r *http.Request){
// Whenever User visits this URL (this function)
// We have to know IP Address of user
output := r.UserAgent()
fmt.Print("Output : ", output)
// But var (output) returns whole string excluding clients ip address
}
答案1
得分: 1
你可以使用Request.RemoteAddr
来获取IP地址。如果这段代码在防火墙、负载均衡器或其他服务后面运行,你还应该查看X-Forwarded-For
头部。
func GetIpAddress(w http.ResponseWriter, r *http.Request) {
ip := r.RemoteAddr
xforward := r.Header.Get("X-Forwarded-For")
fmt.Println("IP : ", ip)
fmt.Println("X-Forwarded-For : ", xforward)
}
请注意,这是一个示例代码片段,用于在Go语言中获取IP地址和X-Forwarded-For头部的值。
英文:
You can use Request.RemoteAddr
You should also take a look at the X-Forwarded-For
header in case this code runs behind a firewall, load balancer or other service.
func GetIpAddress(w http.ResponseWriter, r *http.Request) {
ip := r.RemoteAddr
xforward := r.Header.Get("X-Forwarded-For")
fmt.Println("IP : ", ip)
fmt.Println("X-Forwarded-For : ", xforward)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论