2

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 Answers1

1

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)
}
17xande
  • 2,430
  • 1
  • 24
  • 33