Golang – net/http – How to get client IP address (Real-IP)

Spread the love

For net/http library in Golang for logs or ACL or something else need to get real user IP, especially in variant when golang server behind the reverse proxy.

In this case, need to configure a reverse proxy to the pass all needed headers.

 

For Nginx need to add in location:

proxy_set_header X-Real-IP $remote_addr:$server_port;

In Golang code need to add function:

func GetRealIP(r *http.Request) string {
    IPAddress := r.Header.Get("X-Real-IP")
    if IPAddress == "" {
        IPAddress = r.Header.Get("X-Forwarder-For")
    }
    if IPAddress == "" {
        IPAddress = r.RemoteAddr
    }
    return IPAddress
}

Leave a Reply