github.com/msales/pkg/v3@v3.24.0/httpx/util.go (about)

     1  package httpx
     2  
     3  import (
     4  	"net/http"
     5  	"strings"
     6  )
     7  
     8  // RealIP resolves the real client IP address from the request.
     9  func RealIP(r *http.Request) string {
    10  	hdr := r.Header
    11  	hdrRealIP := hdr.Get("X-Real-Ip")
    12  	hdrForwardedFor := hdr.Get("X-Forwarded-For")
    13  
    14  	if len(hdrForwardedFor) == 0 && len(hdrRealIP) == 0 {
    15  		idx := strings.LastIndex(r.RemoteAddr, ":")
    16  		if idx == -1 {
    17  			return r.RemoteAddr
    18  		}
    19  		return r.RemoteAddr[:idx]
    20  	}
    21  
    22  	if len(hdrForwardedFor) > 0 {
    23  		pieces := strings.Split(hdrForwardedFor, ",")
    24  		return pieces[0]
    25  	}
    26  
    27  	return hdrRealIP
    28  }