How to get client ip address using gorilla/mux – GoLang

huangapple go评论72阅读模式
英文:

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)
}

huangapple
  • 本文由 发表于 2021年9月22日 17:56:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/69281970.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定