-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware_test.go
90 lines (78 loc) · 2.51 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
package pine
import (
"bytes"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestAddingMiddleware(t *testing.T) {
p := New()
if len(p.Middlewares) != 0 {
t.Errorf("middlewares was not expected length %d, instead was %d", 0, len(p.Middlewares))
}
p.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(w, r)
})
})
if len(p.Middlewares) != 1 {
t.Errorf("middlewares was not expected length %d, instead was %d", 1, len(p.Middlewares))
}
}
func TestMiddlewareEarlyReturn(t *testing.T) {
p := New()
p.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
w.Write([]byte("hello from middleware"))
} else {
next.ServeHTTP(w, r)
}
})
})
p.Handle("/testing", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello from handler"))
})
req := httptest.NewRequest("GET", "https://lukaswerner.com/", nil)
resp := httptest.NewRecorder()
p.ServeHTTP(resp, req)
result := resp.Result()
if b, _ := io.ReadAll(result.Body); bytes.Compare(b, []byte("hello from middleware")) != 0 {
t.Errorf("the body response did not match the expected body: %s != %s", string(b), "hello from middleware")
}
req = httptest.NewRequest("GET", "https://lukaswerner.com/testing", nil)
resp = httptest.NewRecorder()
p.ServeHTTP(resp, req)
result = resp.Result()
if b, _ := io.ReadAll(result.Body); bytes.Compare(b, []byte("hello from handler")) != 0 {
t.Errorf("the body response did not match the expected body: %s != %s", string(b), "hello from handler")
}
}
func TestMiddlewareOrdering(t *testing.T) {
p := New()
p.Handle("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello from handler"))
})
var firstMiddlewareCalled time.Time
p.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
firstMiddlewareCalled = time.Now()
next.ServeHTTP(w, r)
})
})
var secondMiddlewareCalled time.Time
p.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
secondMiddlewareCalled = time.Now()
next.ServeHTTP(w, r)
})
})
req := httptest.NewRequest("GET", "https://lukaswerner.com/", nil)
resp := httptest.NewRecorder()
p.ServeHTTP(resp, req)
if secondMiddlewareCalled.Before(firstMiddlewareCalled) {
t.Error("seccond middleware was called before first middleware was called")
}
}