This post demonstrates how to get client IP address in Go web application, even when the app is behind a proxy or a load balancer.
When the web application is served directly to the Internet, we can get the client IP address like this:
func getClientIpAddr(req *http.Request) string {
return req.RemoteAddr
}
In reality, most web applications are served behind proxies and load balancers; we can detect client IP address by retrieving the value from X-Forwarded-For
header. Combining with fallback to the default client IP address from request, we have this little function that does the job:
func getClientIpAddr(req *http.Request) string {
clientIp := req.Header.Get("X-FORWARDED-FOR")
if clientIp != "" {
return clientIp
}
return req.RemoteAddr
}
This is the complete code showing how to get client IP address in Go:
package main
import (
"fmt"
"net/http"
)
func getClientIpAddr(req *http.Request) string {
clientIp := req.Header.Get("X-FORWARDED-FOR")
if clientIp != "" {
return clientIp
}
return req.RemoteAddr
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
clientIp := getClientIpAddr(r)
fmt.Fprintf(w, clientIp+"\n\n")
}
func main() {
http.HandleFunc("/", indexHandler)
http.ListenAndServe(":8080", nil)
}
Have fun!