Go library to retrieve the client IP from HTTP requests.
This library is a port of github.com/pbojinov/request-ip with additional tooling for Go servers.
$ go get github.com/victorkt/clientip
package main
import (
"fmt"
"log"
"net/http"
"github.com/victorkt/clientip"
)
func main() {
http.HandleFunc("/", HelloServer)
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}
func HelloServer(w http.ResponseWriter, r *http.Request) {
ip := clientip.FromRequest(r)
fmt.Fprintf(w, "Hello, your IP is %s!", ip)
}
package main
import (
"fmt"
"log"
"net/http"
"github.com/victorkt/clientip"
)
func main() {
handler := http.HandlerFunc(HelloServer)
http.Handle("/", clientip.Middleware(handler))
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}
func HelloServer(w http.ResponseWriter, r *http.Request) {
ip := clientip.FromContext(r.Context())
fmt.Fprintf(w, "Hello, your IP is %s!", ip)
}
The library will try to get the client IP from a list of headers and falls back on request.RemoteAddr
The order in which the headers are checked is:
- X-Client-IP
- X-Forwarded-For (Header may return multiple IP addresses in the format: "client IP, proxy 1 IP, proxy 2 IP", so we take the the first one.)
- CF-Connecting-IP (Cloudflare)
- Fastly-Client-Ip (Fastly CDN and Firebase hosting header when forwared to a cloud function)
- True-Client-Ip (Akamai and Cloudflare)
- X-Real-IP (Nginx proxy/FastCGI)
- X-Cluster-Client-IP (Rackspace LB, Riverbed Stingray)
- X-Forwarded and Forwarded-For (Variations of #2)
- request.RemoteAddr
If a valid IP was found and it contains a port number, the port will be ignored. If no valid IP is found, it returns a nil
net.IP
The MIT License (MIT) - 2020