0

i have this code where i try to get the localhost ip 127.0.0.1

func (m *Repostory) HomeHandeler(w http.ResponseWriter, r *http.Request) {
    
    // Loop over header names
    for name, values := range r.Header {
        // Loop over all values for the name.
        for _, value := range values {
            fmt.Println(name, value)
        }
    }
    remoteIP := utils.ReadUserIP(r)
}

the result of the loop :

Sec-Ch-Ua " Not A;Brand";v="99", "Chromium";v="102", "Google Chrome";v="102"
Sec-Ch-Ua-Mobile ?0
Cookie csrf_token=4f7iGnCzBTPXwP6snm6Gxxxc3Qe6P9GwVcaR7F3vUtmRuE=; session=yA0nwu4wWMH up79U9ERfzuWg
Accept-Language en,en-US;q=0.9,he;q=0.8
Connection keep-alive
Cache-Control max-age=0
Sec-Ch-Ua-Platform "Windows"
Upgrade-Insecure-Requests 1
User-Agent Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36
Accept text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Mode navigate
Sec-Fetch-User ?1
Accept-Encoding gzip, deflate, br
Sec-Fetch-Site none
Sec-Fetch-Dest document

but the result of remoteIP :

[::1]:55310
user63898
  • 29,839
  • 85
  • 272
  • 514
  • is this is what you are looking for [How do I get the local IP address in Go?](https://stackoverflow.com/questions/23558425/how-do-i-get-the-local-ip-address-in-go) – Manjeet Thakur Jun 27 '22 at 07:53
  • 1
    The IP address is not sent in the HTTP header. It is a property of the underlying TCP connection. – Peter Jun 27 '22 at 08:20
  • i supposed to get it from the request object , like any other request object in any programming language ... – user63898 Jun 27 '22 at 10:55

1 Answers1

0

I'm assuming you're looking for the requester's IP?

You should be able to grab it using the RemoteAddr attribute.

func (m *Repostory) HomeHandeler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "IP: %s", r.RemoteAddr)
}

Or if you're looking for the the servers IP that the request came in on, you can get it from the request's context.

func (m *Repostory) HomeHandeler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "IP: %s", r.Context().Value(http.LocalAddrContextKey))
}

https://pkg.go.dev/net/http#Request

peytoncas
  • 755
  • 3
  • 9