-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcontext_test.go
More file actions
76 lines (67 loc) · 1.96 KB
/
context_test.go
File metadata and controls
76 lines (67 loc) · 1.96 KB
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
package bon
import (
"context"
"net/http"
"testing"
)
var (
TestContextKeyAAA = &struct {
name string
}{
name: "AAA",
}
TestContextKeyBBB = &struct {
name string
}{
name: "BBB",
}
)
type ContextValue struct {
value string
}
func ContextMiddleware(key, value interface{}) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
r = r.WithContext(context.WithValue(r.Context(), key, value))
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}
func TestContext(t *testing.T) {
r := NewRouter()
r.Use(ContextMiddleware(TestContextKeyAAA, &ContextValue{value: "AAA"}))
r.Get("/context1", func(w http.ResponseWriter, r *http.Request) {
v := r.Context().Value(TestContextKeyAAA).(*ContextValue)
_, _ = w.Write([]byte(v.value))
})
r.Get("/context2/:vv", func(w http.ResponseWriter, r *http.Request) {
v := r.Context().Value(TestContextKeyAAA).(*ContextValue)
_, _ = w.Write([]byte(v.value + URLParam(r, "vv")))
})
r.Use(ContextMiddleware(TestContextKeyBBB, &ContextValue{value: "BBB"}))
r.Get("/context3/:vv", func(w http.ResponseWriter, r *http.Request) {
a := r.Context().Value(TestContextKeyAAA).(*ContextValue)
b := r.Context().Value(TestContextKeyBBB).(*ContextValue)
_, _ = w.Write([]byte(a.value + b.value + URLParam(r, "vv")))
})
r.Use(
ContextMiddleware(TestContextKeyAAA, &ContextValue{value: "DDD"}),
ContextMiddleware(TestContextKeyBBB, &ContextValue{value: "EEE"}),
)
r.Get("/context4/:vv", func(w http.ResponseWriter, r *http.Request) {
a := r.Context().Value(TestContextKeyAAA).(*ContextValue)
b := r.Context().Value(TestContextKeyBBB).(*ContextValue)
_, _ = w.Write([]byte(a.value + b.value + URLParam(r, "vv")))
})
if err := Verify(r,
[]*Want{
{"/context1", 200, "DDD"},
{"/context2/bbb", 200, "DDDbbb"},
{"/context3/ccc", 200, "DDDEEEccc"},
{"/context4/fff", 200, "DDDEEEfff"},
},
); err != nil {
t.Fatal(err)
}
}