Skip to content

Commit

Permalink
Allow to specify header keys for GetRequestIPs
Browse files Browse the repository at this point in the history
  • Loading branch information
janos committed Dec 11, 2022
1 parent c12b7bd commit 66ea25b
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,20 @@ import (
)

// GetRequestIPs returns all possible IPs found in HTTP request.
func GetRequestIPs(r *http.Request) string {
func GetRequestIPs(r *http.Request, realIPHeaders ...string) string {
if realIPHeaders == nil {
realIPHeaders = []string{"X-Forwarded-For", "X-Real-Ip"}
}
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
ip = r.RemoteAddr
}
ips := []string{ip}
xfr := r.Header.Get("X-Forwarded-For")
if xfr != "" {
ips = append(ips, xfr)
}
xri := r.Header.Get("X-Real-Ip")
if xri != "" {
ips = append(ips, xri)
for _, key := range realIPHeaders {
v := r.Header.Get(key)
if v != "" {
ips = append(ips, v)
}
}
return strings.Join(ips, ", ")
}
Expand Down

0 comments on commit 66ea25b

Please sign in to comment.