-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmw_test.go
More file actions
75 lines (62 loc) · 1.75 KB
/
mw_test.go
File metadata and controls
75 lines (62 loc) · 1.75 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
package mw_test
import (
"github.com/collinglass/mw"
"net/http"
"testing"
)
// Create middleware from scratch
func CreatedMiddleware() mw.Middleware {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Set JSON Response Header
w.WriteHeader(http.StatusCreated)
h.ServeHTTP(w, r)
})
}
}
// Create middleware from scratch
func JSONMiddleware() mw.Middleware {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Set JSON Response Header
w.Header().Set("Content-Type", "application/json")
h.ServeHTTP(w, r)
})
}
}
func TestDecorate(t *testing.T) {
// new router
r := http.NewServeMux()
expectedContentType := "application/json"
expectedStatus := http.StatusCreated
r.HandleFunc("/api/data", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"data":"json"}`))
})
// decorate router
server := mw.Decorate(
r,
CreatedMiddleware(),
JSONMiddleware(),
)
http.Handle("/api/", server)
go http.ListenAndServe(":8080", nil)
c := http.Client{}
req, err := http.NewRequest("GET", "http://localhost:8080/api/data", nil)
if err != nil {
t.Errorf("error creating request: %s\n", err)
}
resp, err := c.Do(req)
if err != nil {
t.Errorf("error making request: %s\n", err)
}
// checks if JSONMiddlware was called
actualContentType := resp.Header.Get("Content-Type")
if expectedContentType != actualContentType {
t.Errorf("expected %s and got %s", expectedContentType, actualContentType)
}
// checks if CreatedMiddleware was called
actualStatus := resp.StatusCode
if expectedStatus != actualStatus {
t.Errorf("expected %s and got %s", expectedContentType, actualContentType)
}
}