This repository has been archived by the owner on Jul 6, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathIP_test.go
102 lines (87 loc) · 2 KB
/
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// Copyright (c) 2018 Shen Sheng
// Copyright (c) 2019 Eduard Urbach
package aero
import (
"net/http"
"testing"
)
func TestIsPrivateAddress(t *testing.T) {
testData := map[string]bool{
"127.0.0.0": true,
"10.0.0.0": true,
"169.254.0.0": true,
"192.168.0.0": true,
"::1": true,
"fc00::": true,
"172.15.0.0": false,
"172.16.0.0": true,
"172.31.0.0": true,
"172.32.0.0": false,
"147.12.56.11": false,
}
for addr, isLocal := range testData {
isPrivate, err := isPrivateAddress(addr)
if err != nil {
t.Errorf("fail processing %s: %v", addr, err)
}
if isPrivate != isLocal {
format := "%s should "
if !isLocal {
format += "not "
}
format += "be local address"
t.Errorf(format, addr)
}
}
}
func TestRealIP(t *testing.T) {
// Create type and function for testing
type testIP struct {
name string
request *http.Request
expected string
}
newRequest := func(remoteAddr, xRealIP string, xForwardedFor ...string) *http.Request {
h := http.Header{}
h.Set("X-Real-IP", xRealIP)
for _, address := range xForwardedFor {
h.Set("X-Forwarded-For", address)
}
return &http.Request{
RemoteAddr: remoteAddr,
Header: h,
}
}
// Create test data
publicAddr1 := "144.12.54.87"
publicAddr2 := "119.14.55.11"
localAddr := "127.0.0.0"
testData := []testIP{
{
name: "No header",
request: newRequest(publicAddr1, ""),
expected: publicAddr1,
},
{
name: "Has X-Forwarded-For",
request: newRequest("", "", publicAddr1),
expected: publicAddr1,
},
{
name: "Has multiple X-Forwarded-For",
request: newRequest("", "", localAddr, publicAddr1, publicAddr2),
expected: publicAddr2,
},
{
name: "Has X-Real-IP",
request: newRequest("", publicAddr1),
expected: publicAddr1,
},
}
// Run the test
for _, v := range testData {
if actual := realIP(v.request); v.expected != actual {
t.Errorf("%s: expected %s but get %s", v.name, v.expected, actual)
}
}
}