Skip to content

Instantly share code, notes, and snippets.

@lucas-code42
Forked from miguelmota/ip.go
Created March 31, 2024 22:42
Show Gist options
  • Save lucas-code42/88d2ea0b9b4464e0f5e2c21d1c2934a3 to your computer and use it in GitHub Desktop.
Save lucas-code42/88d2ea0b9b4464e0f5e2c21d1c2934a3 to your computer and use it in GitHub Desktop.
Golang get IP address from web HTTP request handler
package main
import (
"errors"
"log"
"net"
"net/http"
"strings"
)
// getIP returns the ip address from the http request
func getIP(r *http.Request) (string, error) {
ips := r.Header.Get("X-Forwarded-For")
splitIps := strings.Split(ips, ",")
if len(splitIps) > 0 {
// get last IP in list since ELB prepends other user defined IPs, meaning the last one is the actual client IP.
netIP := net.ParseIP(splitIps[len(splitIps)-1])
if netIP != nil {
return netIP.String(), nil
}
}
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return "", err
}
netIP := net.ParseIP(ip)
if netIP != nil {
ip := netIP.String()
if ip == "::1" {
return "127.0.0.1", nil
}
return ip, nil
}
return "", errors.New("IP not found")
}
func handler(w http.ResponseWriter, r *http.Request) {
ip, err := getIP(r)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(ip))
}
func main() {
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment