forked from Desuuuu/traefik-real-ip-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
real_ip.go
97 lines (81 loc) · 1.9 KB
/
real_ip.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
97
package traefik_real_ip_plugin
import (
"context"
"errors"
"fmt"
"net"
"net/http"
)
type RetrieverConfig struct {
Header string `json:"header"`
ProxyCIDRs []string `json:"proxyCIDRs,omitempty"`
ProxyCount int `json:"proxyCount,omitempty"`
}
type Config struct {
Retrievers []RetrieverConfig `json:"retrievers,omitempty"`
Headers []string `json:"headers,omitempty"`
}
func CreateConfig() *Config {
return &Config{
Retrievers: nil,
Headers: nil,
}
}
type RealIP struct {
next http.Handler
name string
retrievers []Retriever
headers []string
}
func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
if config == nil {
return nil, errors.New("invalid config")
}
ri := &RealIP{
next: next,
name: name,
headers: append([]string{}, config.Headers...),
}
for _, rc := range config.Retrievers {
if rc.Header == "" {
continue
}
switch {
case len(rc.ProxyCIDRs) > 0:
cidrs := make([]*net.IPNet, 0, len(rc.ProxyCIDRs))
for _, c := range rc.ProxyCIDRs {
_, cidr, err := net.ParseCIDR(c)
if err != nil {
return nil, fmt.Errorf("invalid CIDR: %w", err)
}
cidrs = append(cidrs, cidr)
}
ri.retrievers = append(ri.retrievers, &ProxyCIDRRetriever{
Header: rc.Header,
CIDRs: cidrs,
})
case rc.ProxyCount > 0:
ri.retrievers = append(ri.retrievers, &ProxyCountRetriever{
Header: rc.Header,
Count: rc.ProxyCount,
})
default:
ri.retrievers = append(ri.retrievers, &HeaderRetriever{
Header: rc.Header,
})
}
}
return ri, nil
}
func (ri *RealIP) ServeHTTP(w http.ResponseWriter, r *http.Request) {
for _, retriever := range ri.retrievers {
if ip := retriever.Retrieve(r.Header); ip != nil {
ipStr := ip.String()
for _, header := range ri.headers {
r.Header.Set(header, ipStr)
}
break
}
}
ri.next.ServeHTTP(w, r)
}