/
content_type_checker_test.go
48 lines (37 loc) · 1.56 KB
/
content_type_checker_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
package rest
import (
"github.com/ant0ine/go-json-rest/rest/test"
"testing"
)
func TestContentTypeCheckerMiddleware(t *testing.T) {
api := NewApi()
// the middleware to test
api.Use(&ContentTypeCheckerMiddleware{})
// a simple app
api.SetApp(AppSimple(func(w ResponseWriter, r *Request) {
w.WriteJson(map[string]string{"Id": "123"})
}))
// wrap all
handler := api.MakeHandler()
// no payload, no content length, no check
recorded := test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://localhost/", nil))
recorded.CodeIs(200)
// JSON payload with correct content type
recorded = test.RunRequest(t, handler, test.MakeSimpleRequest("POST", "http://localhost/", map[string]string{"Id": "123"}))
recorded.CodeIs(200)
// JSON payload with correct content type specifying the utf-8 charset
req := test.MakeSimpleRequest("POST", "http://localhost/", map[string]string{"Id": "123"})
req.Header.Set("Content-Type", "application/json; charset=utf-8")
recorded = test.RunRequest(t, handler, req)
recorded.CodeIs(200)
// JSON payload with incorrect content type
req = test.MakeSimpleRequest("POST", "http://localhost/", map[string]string{"Id": "123"})
req.Header.Set("Content-Type", "text/x-json")
recorded = test.RunRequest(t, handler, req)
recorded.CodeIs(415)
// JSON payload with correct content type but incorrect charset
req = test.MakeSimpleRequest("POST", "http://localhost/", map[string]string{"Id": "123"})
req.Header.Set("Content-Type", "application/json; charset=ISO-8859-1")
recorded = test.RunRequest(t, handler, req)
recorded.CodeIs(415)
}