【问题标题】:How to get client ip address using gorilla/mux - GoLang [duplicate]如何使用 gorilla/mux 获取客户端 IP 地址 - GoLang [重复]
【发布时间】:2025-11-23 06:05:01
【问题描述】:

我正在使用 gorilla/mux 在 golang 中实现一个 API 应用程序,这是一个强大的库,有助于构建 Web API,

但是我需要为每个客户保留 IP 地址,我如何才能为每个访问网站的客户获取 IP 地址?

代码:

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
}

【问题讨论】:

  • 你能包含一些你到目前为止写的代码吗?
  • @17xande 你去...

标签: go mux


【解决方案1】:

您可以使用Request.RemoteAddr
您还应该查看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)
}

【讨论】: