| 1 | package goji |
| 2 | |
| 3 | import ( |
| 4 | "net/http" |
| 5 | "testing" |
| 6 | ) |
| 7 | |
| 8 | func expectSequence(t *testing.T, ch chan string, seq ...string) { |
| 9 | for i, str := range seq { |
| 10 | if msg := <-ch; msg != str { |
| 11 | t.Errorf("[%d] expected %s, got %s", i, str, msg) |
| 12 | } |
| 13 | } |
| 14 | } |
| 15 | |
| 16 | func TestMiddleware(t *testing.T) { |
| 17 | t.Parallel() |
| 18 | |
| 19 | m := NewMux() |
| 20 | ch := make(chan string, 10) |
| 21 | m.Use(func(h http.Handler) http.Handler { |
| 22 | fn := func(w http.ResponseWriter, r *http.Request) { |
| 23 | ch <- "before one" |
| 24 | h.ServeHTTP(w, r) |
| 25 | ch <- "after one" |
| 26 | } |
| 27 | return http.HandlerFunc(fn) |
| 28 | }) |
| 29 | m.Use(func(h http.Handler) http.Handler { |
| 30 | fn := func(w http.ResponseWriter, r *http.Request) { |
| 31 | ch <- "before two" |
| 32 | h.ServeHTTP(w, r) |
| 33 | ch <- "after two" |
| 34 | } |
| 35 | return http.HandlerFunc(fn) |
| 36 | }) |
| 37 | m.Handle(boolPattern(true), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 38 | ch <- "handler" |
| 39 | })) |
| 40 | |
| 41 | m.ServeHTTP(wr()) |
| 42 | |
| 43 | expectSequence(t, ch, "before one", "before two", "handler", "after two", "after one") |
| 44 | } |
| 45 | |
| 46 | func makeMiddleware(ch chan string, name string) func(http.Handler) http.Handler { |
| 47 | return func(h http.Handler) http.Handler { |
| 48 | fn := func(w http.ResponseWriter, r *http.Request) { |
| 49 | ch <- "before " + name |
| 50 | h.ServeHTTP(w, r) |
| 51 | ch <- "after " + name |
| 52 | } |
| 53 | return http.HandlerFunc(fn) |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | func TestMiddlewareReconfigure(t *testing.T) { |
| 58 | t.Parallel() |
| 59 | |
| 60 | m := NewMux() |
| 61 | ch := make(chan string, 10) |
| 62 | m.Use(makeMiddleware(ch, "one")) |
| 63 | m.Use(makeMiddleware(ch, "two")) |
| 64 | m.Handle(boolPattern(true), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 65 | ch <- "handler" |
| 66 | })) |
| 67 | |
| 68 | w, r := wr() |
| 69 | m.ServeHTTP(w, r) |
| 70 | |
| 71 | expectSequence(t, ch, "before one", "before two", "handler", "after two", "after one") |
| 72 | |
| 73 | m.Use(makeMiddleware(ch, "three")) |
| 74 | |
| 75 | w, r = wr() |
| 76 | m.ServeHTTP(w, r) |
| 77 | |
| 78 | expectSequence(t, ch, "before one", "before two", "before three", |
| 79 | "handler", "after three", "after two", "after one") |
| 80 | } |