-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
80 lines (67 loc) · 1.71 KB
/
Copy pathexample_test.go
File metadata and controls
80 lines (67 loc) · 1.71 KB
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
package ip_test
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"github.com/skarm/ip"
)
func ExampleNew() {
extractor := ip.Must(ip.New(
ip.WithTrustedProxies("10.0.0.0/8"),
))
addr, err := extractor.ExtractFrom(map[string][]string{
ip.XForwardedFor: {"198.51.100.7, 10.0.0.1"},
}, "10.0.0.2:443")
if err != nil {
panic(err)
}
fmt.Println(addr)
// Output:
// 198.51.100.7
}
func ExampleExtractor_ExtractResultFrom() {
extractor := ip.Must(ip.New(
ip.WithTrustedProxies("10.0.0.0/8"),
))
result, err := extractor.ExtractResultFrom(map[string][]string{
ip.XForwardedFor: {"198.51.100.7, 10.0.0.1"},
}, "10.0.0.2:443")
if err != nil {
panic(err)
}
fmt.Println(result.Addr)
fmt.Println(result.Header)
fmt.Println(result.TrustedHops)
fmt.Println(result.Source == ip.SourceProxyHeader)
fmt.Println(result.Reason == ip.ReasonSelectedHeader)
// Output:
// 198.51.100.7
// x-forwarded-for
// 2
// true
// true
}
func ExampleExtractor_MiddlewareWithErrorHandler() {
extractor := ip.Must(ip.New(
ip.WithStrict(),
ip.WithTrustedProxies("10.0.0.0/8"),
))
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
addr, _ := ip.Ctx(r.Context())
fmt.Fprintln(w, addr)
})
request := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "https://service.example", nil)
request.RemoteAddr = "10.0.0.2:443"
request.Header.Set(ip.XForwardedFor, "not-an-ip")
response := httptest.NewRecorder()
extractor.MiddlewareWithErrorHandler(
next,
func(w http.ResponseWriter, _ *http.Request, _ error) {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
},
).ServeHTTP(response, request)
fmt.Println(response.Code)
// Output:
// 400
}