-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmethodswitch_test.go
58 lines (53 loc) · 1.53 KB
/
methodswitch_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
package httptools
import (
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"testing"
)
func TestMethodSwitch(t *testing.T) {
h := MethodSwitch{
"GET": http.HandlerFunc(handlerA),
"POST": http.HandlerFunc(handlerB),
"PUT": http.HandlerFunc(handlerC),
}
rr := httptest.NewRecorder()
h.ServeHTTP(rr, MustRequest(http.NewRequest("GET", "/", nil)))
expected := []string{"a"}
got := rr.HeaderMap["Handler"]
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("POST", "/", nil)))
expected = []string{"b"}
got = rr.HeaderMap["Handler"]
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("PUT", "/", nil)))
expected = []string{"c"}
got = rr.HeaderMap["Handler"]
if !reflect.DeepEqual(got, expected) {
t.Fatalf("Header list wrong. Expected %#v, got %#v", expected, got)
}
}
func ExampleMethodSwitch() {
ms := MethodSwitch{
"GET": http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("A GET request")
}),
"POST": http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("A POST request")
}),
}
req, _ := http.NewRequest("GET", "/", nil)
ms.ServeHTTP(httptest.NewRecorder(), req)
req, _ = http.NewRequest("POST", "/", nil)
ms.ServeHTTP(httptest.NewRecorder(), req)
// Output:
// A GET request
// A POST request
}