-
Notifications
You must be signed in to change notification settings - Fork 739
/
httputil.go
87 lines (72 loc) · 2.18 KB
/
httputil.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package httputil
import (
"net"
"net/http"
"strings"
"github.com/prebid/prebid-server/v2/util/iputil"
)
var (
trueClientIP = http.CanonicalHeaderKey("True-Client-IP")
xForwardedFor = http.CanonicalHeaderKey("X-Forwarded-For")
xRealIP = http.CanonicalHeaderKey("X-Real-IP")
)
type ContentEncoding string
const (
ContentEncodingGZIP ContentEncoding = "gzip"
)
func (k ContentEncoding) Normalize() ContentEncoding {
return ContentEncoding(strings.ToLower(string(k)))
}
// FindIP returns the first ip address found in the http request matching the predicate v.
func FindIP(r *http.Request, v iputil.IPValidator) (net.IP, iputil.IPVersion) {
if ip, ver := findTrueClientIP(r, v); ip != nil {
return ip, ver
}
if ip, ver := findForwardedFor(r, v); ip != nil {
return ip, ver
}
if ip, ver := findRealIP(r, v); ip != nil {
return ip, ver
}
if ip, ver := findRemoteAddr(r, v); ip != nil {
return ip, ver
}
return nil, iputil.IPvUnknown
}
func findTrueClientIP(r *http.Request, v iputil.IPValidator) (net.IP, iputil.IPVersion) {
if value := r.Header.Get(trueClientIP); value != "" {
value = strings.TrimSpace(value)
if ip, ver := iputil.ParseIP(value); ip != nil && v.IsValid(ip, ver) {
return ip, ver
}
}
return nil, iputil.IPvUnknown
}
func findForwardedFor(r *http.Request, v iputil.IPValidator) (net.IP, iputil.IPVersion) {
if value := r.Header.Get(xForwardedFor); value != "" {
for _, p := range strings.Split(value, ",") {
p = strings.TrimSpace(p)
if ip, ver := iputil.ParseIP(p); ip != nil && v.IsValid(ip, ver) {
return ip, ver
}
}
}
return nil, iputil.IPvUnknown
}
func findRealIP(r *http.Request, v iputil.IPValidator) (net.IP, iputil.IPVersion) {
if value := r.Header.Get(xRealIP); value != "" {
value = strings.TrimSpace(value)
if ip, ver := iputil.ParseIP(value); ip != nil && v.IsValid(ip, ver) {
return ip, ver
}
}
return nil, iputil.IPvUnknown
}
func findRemoteAddr(r *http.Request, v iputil.IPValidator) (net.IP, iputil.IPVersion) {
if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
if ip, ver := iputil.ParseIP(host); ip != nil && v.IsValid(ip, ver) {
return ip, ver
}
}
return nil, iputil.IPvUnknown
}