forked from sebest/xff
-
Notifications
You must be signed in to change notification settings - Fork 0
/
xff.go
81 lines (73 loc) · 1.85 KB
/
xff.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
package xff
import (
"net"
"net/http"
"strings"
)
var privateMasks = func() []net.IPNet {
masks := []net.IPNet{}
for _, cidr := range []string{"10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"} {
_, net, err := net.ParseCIDR(cidr)
if err != nil {
panic(err)
}
masks = append(masks, *net)
}
return masks
}()
// IsPublicIP returns true if the given IP can be routed on the Internet
func IsPublicIP(ip net.IP) bool {
if !ip.IsGlobalUnicast() {
return false
}
for _, mask := range privateMasks {
if mask.Contains(ip) {
return false
}
}
return true
}
// Parse parses the value of the X-Forwarded-For Header and returns the IP address.
func Parse(ipList string) string {
for _, ip := range strings.Split(ipList, ",") {
ip = strings.TrimSpace(ip)
if IP := net.ParseIP(ip); IP != nil && IsPublicIP(IP) {
return ip
}
}
return ""
}
// GetRemoteAddr parses the given request, resolves the X-Forwarded-For header
// and returns the resolved remote address.
func GetRemoteAddr(r *http.Request) string {
xff := r.Header.Get("X-Forwarded-For")
var ip, port string
if xff != "" {
ip = Parse(xff)
}
if _, oport, err := net.SplitHostPort(r.RemoteAddr); err == nil {
port = oport
} else {
port = "unknown"
}
if ip != "" {
return net.JoinHostPort(ip, port)
}
return r.RemoteAddr
}
// Handler is a middleware to update RemoteAdd from X-Fowarded-* Headers.
func Handler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.RemoteAddr = GetRemoteAddr(r)
h.ServeHTTP(w, r)
})
}
// HandlerFunc is a Martini compatible handler
func HandlerFunc(w http.ResponseWriter, r *http.Request) {
r.RemoteAddr = GetRemoteAddr(r)
}
// XFF is a Negroni compatible interface
func XFF(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
r.RemoteAddr = GetRemoteAddr(r)
next(w, r)
}