-
Notifications
You must be signed in to change notification settings - Fork 2
/
middleware_test.go
47 lines (39 loc) · 1010 Bytes
/
middleware_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
package clientip
import (
"fmt"
"net"
"net/http"
"net/http/httptest"
"reflect"
"testing"
)
func TestMiddleware(t *testing.T) {
t.Parallel()
var handlerCalled bool
fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handlerCalled = true
ip := FromContext(r.Context())
expectedIP := net.ParseIP("45.0.0.40")
if !reflect.DeepEqual(expectedIP, ip) {
t.Errorf("expected client IP from request to equal %s, got: %s", expectedIP, ip)
}
_, _ = fmt.Fprintln(w, "hello world")
})
srv := httptest.NewServer(Middleware(fn))
defer srv.Close()
req, err := http.NewRequest("POST", srv.URL, nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("x-forwarded-for", "45.0.0.40")
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
if res.StatusCode != http.StatusOK {
t.Errorf("expected response http code %d, got: %d", http.StatusOK, res.StatusCode)
}
if !handlerCalled {
t.Error("expected test handler to have been called but didn't")
}
}