-
Notifications
You must be signed in to change notification settings - Fork 0
/
remote.go
63 lines (51 loc) · 1.34 KB
/
remote.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
package remote
import (
"fmt"
"net"
"net/http"
"strings"
)
// IP contains simplified IP information that includes first, second, and last IP in the list of forwarded IPs
type IP struct {
IPCount int8
IP1 string
IP2 string
IPLast string
}
// GetIP returns the remote IP for the given http.Request. It checks optional CF-Connecting-IP and X-FORWARDED-FOR headers.
func GetIP(r *http.Request) (*IP, error) {
info := &IP{}
cloudflareIP := r.Header.Get("CF-Connecting-IP")
if len(cloudflareIP) > 0 {
if err := parseIPs(cloudflareIP, info); err != nil {
return nil, fmt.Errorf("GetIP failed to parseIPs %q", cloudflareIP)
}
return info, nil
}
xff := r.Header.Get("X-FORWARDED-FOR")
if len(xff) > 0 {
if err := parseIPs(xff, info); err != nil {
return nil, fmt.Errorf("GetIP failed to parseIPs %q", xff)
}
return info, nil
}
info.IPCount = 1
info.IP1, _, _ = net.SplitHostPort(r.RemoteAddr)
info.IPLast = info.IP1
return info, nil
}
func parseIPs(s string, info *IP) error {
ips := strings.Split(s, ",")
for _, ip := range ips {
if net.ParseIP(ip) == nil {
return fmt.Errorf("parseIPs failed to net.ParseIP %q", ip)
}
}
info.IPCount = int8(len(ips))
info.IP1 = strings.TrimSpace(ips[0])
if len(ips) > 1 {
info.IP2 = strings.TrimSpace(ips[1])
}
info.IPLast = strings.TrimSpace(ips[len(ips)-1])
return nil
}