This package is useful to get the client IP address of incoming HTTP requests in GoLang.
Inspired by Petar Bojinov
It looks for specific headers in the request and falls back to some defaults if they do not exist.
The client ip is determined by the following order:
- X-Client-IP
- X-Forwarded-For (Header may return multiple IP addresses in the format:"clientIP, proxy1 IP, proxy2 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, Forwarded-For and Forwarded (Variations of #2)
- req.RemoteAddr
If an IP address cannot be found, it will return empty string.
Use the go command:
go get "github.com/vikram1565/request-ip"
package main
import (
"log"
"net/http"
rip "github.com/vikram1565/request-ip"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
log.Println("Your client ip is ", rip.GetClientIP(r))
})
log.Println("server started on: http://127.0.1.1:8000")
serverError := http.ListenAndServe(":8000", nil)
if serverError != nil {
log.Println("Failed to start server: ", serverError)
}
}
on localhost you'll see ::1 or 127.0.0.1 if you're using IPv4 , ::ffff:127.0.0.1 if you're using IPv6
You may have noticed that when you browse to different domains, your browser is sending requests for http://<your.domain.com>/favicon.ico, behind the scenes. Thats why my log is printed twice.
- Special thanks to @Akshay Bharambe for code review.
Copyright (C) 2020 by Vikram Ingawale [GitHub]
request-ip package released under MIT License. See LICENSE for details.