Get the IP Address of a HTTP Request

· 170 words · 1 minute read

This post demonstrates how to get the IP address of incoming HTTP requests in Go. As a function, it attempts to use the X-FORWARDED-FOR http header for code behind proxies and load balancers (such as on hosts like Heroku) while falling back to the RemoteAddr if the header isn’t found.

Just as an example, we created an echo server (of sorts) below to reply to incoming requests with the requesting ip address in json form.

package main

import (
	"encoding/json"
	"net/http"
)

func main() {
	http.HandleFunc("/", ExampleHandler)
	if err := http.ListenAndServe(":8080", nil); err != nil {
		panic(err)
	}
}

func ExampleHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("Content-Type", "application/json")
	resp, _ := json.Marshal(map[string]string{
		"ip": GetIP(r),
	})
	w.Write(resp)
}

// GetIP gets a requests IP address by reading off the forwarded-for
// header (for proxies) and falls back to use the remote address.
func GetIP(r *http.Request) string {
	forwarded := r.Header.Get("X-FORWARDED-FOR")
	if forwarded != "" {
		return forwarded
	}
	return r.RemoteAddr
}

get http request ip address

(ignore the printf - it’s just to keep the output tidy)

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!