-
Notifications
You must be signed in to change notification settings - Fork 2
/
real_ip_test.go
75 lines (62 loc) · 1.54 KB
/
real_ip_test.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
package traefik_real_ip_test
import (
"context"
"net/http"
"net/http/httptest"
"testing"
plugin "github.com/jramsgz/traefik-real-ip"
)
func TestNew(t *testing.T) {
cfg := plugin.CreateConfig()
cfg.ExcludedNets = []string{"127.0.0.1/24"}
ctx := context.Background()
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {})
handler, err := plugin.New(ctx, next, cfg, "traefik-real-ip")
if err != nil {
t.Fatal(err)
}
testCases := []struct {
header string
desc string
xForwardedFor string
expected string
}{
{
header: "X-Forwarded-For",
desc: "don't forward",
xForwardedFor: "127.0.0.2",
expected: "",
},
{
header: "X-Forwarded-For",
desc: "forward",
xForwardedFor: "10.0.0.1",
expected: "",
},
{
header: "Cf-Connecting-Ip",
desc: "forward",
xForwardedFor: "10.0.0.1",
expected: "10.0.0.1",
},
}
for _, test := range testCases {
test := test
t.Run(test.desc, func(t *testing.T) {
recorder := httptest.NewRecorder()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set(test.header, test.xForwardedFor)
handler.ServeHTTP(recorder, req)
assertHeader(t, req, "X-Real-Ip", test.expected)
})
}
}
func assertHeader(t *testing.T, req *http.Request, key, expected string) {
t.Helper()
if req.Header.Get(key) != expected {
t.Errorf("invalid header value: %s", req.Header.Get(key))
}
}