-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware_test.go
91 lines (78 loc) · 2.16 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
81
82
83
84
85
86
87
88
89
90
91
package apex_test
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/RexterR/apex"
"github.com/RexterR/apex/adapter"
"github.com/julienschmidt/httprouter"
"github.com/stretchr/testify/require"
)
func TestCreateMiddleware(t *testing.T) {
mw := apex.Middleware(func(next http.Handler) http.Handler {
return nil
})
require.NotNil(t, mw)
}
func TestRunMiddleware(t *testing.T) {
var result string
mw := apex.Middleware(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
result += "Hello, "
next.ServeHTTP(w, r)
})
})
mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
result += "world!"
})).ServeHTTP(nil, nil)
require.Equal(t, "Hello, world!", result)
}
func TestComposeMiddleware(t *testing.T) {
var result string
first := apex.Middleware(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
result += "Hello, "
next.ServeHTTP(w, r)
})
})
second := apex.Middleware(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
result += "world "
next.ServeHTTP(w, r)
})
})
mw := first.Then(second)
mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
result += "again!"
})).ServeHTTP(nil, nil)
require.Equal(t, "Hello, world again!", result)
}
func TestUseMiddleware(t *testing.T) {
h := &adapter.Httprouter{Router: httprouter.New()}
m := apex.New(h)
var count int8
mw := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
count++
next.ServeHTTP(w, r)
})
}
secondMw := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
count++
next.ServeHTTP(w, r)
})
}
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
count++
})
m.Use(mw)
m.Use(secondMw)
m.Get("/test", handler)
m.Post("/test", handler)
ts := httptest.NewServer(m)
defer ts.Close()
_, _ = http.Get(ts.URL + "/test")
_, _ = http.Post(ts.URL+"/test", "text/plain", nil)
require.Equal(t, int8(6), count)
}