github.com/letsencrypt/boulder@v0.20251208.0/web/extract.go (about)

     1  package web
     2  
     3  import (
     4  	"net"
     5  	"net/http"
     6  	"net/netip"
     7  )
     8  
     9  // ExtractRequesterIP extracts the IP address of the requester from the HTTP
    10  // request. It first checks the "X-Real-IP" header, and if that is not set, it
    11  // falls back to the RemoteAddr field of the request. An error is returned if
    12  // the IP address cannot be determined.
    13  func ExtractRequesterIP(req *http.Request) (netip.Addr, error) {
    14  	ip, err := netip.ParseAddr(req.Header.Get("X-Real-IP"))
    15  	if err == nil {
    16  		return ip, nil
    17  	}
    18  	host, _, err := net.SplitHostPort(req.RemoteAddr)
    19  	if err != nil {
    20  		return netip.Addr{}, err
    21  	}
    22  	return netip.ParseAddr(host)
    23  }