forked from Desuuuu/traefik-real-ip-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
retriever.go
96 lines (75 loc) · 1.41 KB
/
retriever.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
88
89
90
91
92
93
94
95
96
package traefik_real_ip_plugin
import (
"net"
"net/http"
"strings"
)
type Retriever interface {
Retrieve(http.Header) net.IP
}
type HeaderRetriever struct {
Header string
}
func (r *HeaderRetriever) Retrieve(headers http.Header) net.IP {
for _, value := range headers.Values(r.Header) {
if value == "" {
continue
}
if ip := net.ParseIP(strings.TrimSpace(value)); ip != nil {
return ip
}
}
return nil
}
type ProxyCountRetriever struct {
Header string
Count int
}
func (r *ProxyCountRetriever) Retrieve(headers http.Header) net.IP {
if r.Count < 1 {
return nil
}
for _, value := range headers.Values(r.Header) {
if value == "" {
continue
}
list := strings.Split(value, ",")
i := len(list) - r.Count
if i < 0 {
continue
}
if ip := net.ParseIP(strings.TrimSpace(list[i])); ip != nil {
return ip
}
}
return nil
}
type ProxyCIDRRetriever struct {
Header string
CIDRs []*net.IPNet
}
func (r *ProxyCIDRRetriever) Retrieve(headers http.Header) net.IP {
for _, value := range headers.Values(r.Header) {
if value == "" {
continue
}
list := strings.Split(value, ",")
for i := len(list) - 1; i >= 0; i-- {
ip := net.ParseIP(strings.TrimSpace(list[i]))
if ip == nil {
break
}
isProxy := false
for _, cidr := range r.CIDRs {
if cidr.Contains(ip) {
isProxy = true
break
}
}
if !isProxy {
return ip
}
}
}
return nil
}