-
Notifications
You must be signed in to change notification settings - Fork 5
/
mounts_test.go
68 lines (62 loc) · 1.96 KB
/
mounts_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
package httptools
import (
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"testing"
)
func TestMounts_Stripping(t *testing.T) {
h := Mounts{
"/first/handler": http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Path", r.URL.Path)
}),
"/second/handler/": http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Path", r.URL.Path)
}),
}
rr := httptest.NewRecorder()
h.ServeHTTP(rr, MustRequest(http.NewRequest("GET", "/first/handler/and/a/path", nil)))
expected := []string{"/and/a/path"}
expectedCode := http.StatusOK
got := rr.HeaderMap["X-Path"]
if rr.Code != expectedCode {
t.Fatalf("Unexpected error code. Expected %d, got %d", expectedCode, rr.Code)
}
if !reflect.DeepEqual(got, expected) {
t.Fatalf("Header list wrong. Expected %#v, got %#v", expected, got)
}
rr = httptest.NewRecorder()
h.ServeHTTP(rr, MustRequest(http.NewRequest("GET", "/second/handler/and/a/path", nil)))
expected = []string{"/and/a/path"}
expectedCode = http.StatusOK
got = rr.HeaderMap["X-Path"]
if rr.Code != expectedCode {
t.Fatalf("Unexpected error code. Expected %d, got %d", expectedCode, rr.Code)
}
if !reflect.DeepEqual(got, expected) {
t.Fatalf("Header list wrong. Expected %#v, got %#v", expected, got)
}
rr = httptest.NewRecorder()
h.ServeHTTP(rr, MustRequest(http.NewRequest("GET", "/third/handler/and/a/path", nil)))
expectedCode = http.StatusNotFound
if rr.Code != expectedCode {
t.Fatalf("Unexpected error code. Expected %d, got %d", expectedCode, rr.Code)
}
}
func ExampleMounts() {
ms := Mounts{
"/api/": Mounts{
"/cars": http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("Request path:", r.URL.Path)
}),
"/people": http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// ...
}),
},
}
req, _ := http.NewRequest("GET", "/api/cars/bentley", nil)
ms.ServeHTTP(httptest.NewRecorder(), req)
// Output:
// Request path: /bentley
}