-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware_test.go
80 lines (66 loc) · 1.82 KB
/
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
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 goji
import (
"net/http"
"testing"
)
func expectSequence(t *testing.T, ch chan string, seq ...string) {
for i, str := range seq {
if msg := <-ch; msg != str {
t.Errorf("[%d] expected %s, got %s", i, str, msg)
}
}
}
func TestMiddleware(t *testing.T) {
t.Parallel()
m := NewMux()
ch := make(chan string, 10)
m.Use(func(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ch <- "before one"
h.ServeHTTP(w, r)
ch <- "after one"
}
return http.HandlerFunc(fn)
})
m.Use(func(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ch <- "before two"
h.ServeHTTP(w, r)
ch <- "after two"
}
return http.HandlerFunc(fn)
})
m.Handle(boolPattern(true), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ch <- "handler"
}))
m.ServeHTTP(wr())
expectSequence(t, ch, "before one", "before two", "handler", "after two", "after one")
}
func makeMiddleware(ch chan string, name string) func(http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ch <- "before " + name
h.ServeHTTP(w, r)
ch <- "after " + name
}
return http.HandlerFunc(fn)
}
}
func TestMiddlewareReconfigure(t *testing.T) {
t.Parallel()
m := NewMux()
ch := make(chan string, 10)
m.Use(makeMiddleware(ch, "one"))
m.Use(makeMiddleware(ch, "two"))
m.Handle(boolPattern(true), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ch <- "handler"
}))
w, r := wr()
m.ServeHTTP(w, r)
expectSequence(t, ch, "before one", "before two", "handler", "after two", "after one")
m.Use(makeMiddleware(ch, "three"))
w, r = wr()
m.ServeHTTP(w, r)
expectSequence(t, ch, "before one", "before two", "before three",
"handler", "after three", "after two", "after one")
}