This repository was archived by the owner on Jul 2, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.go
More file actions
60 lines (50 loc) · 1.77 KB
/
Copy pathmiddleware.go
File metadata and controls
60 lines (50 loc) · 1.77 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
package bourbon
import (
"encoding/json"
"fmt"
"net/http"
"reflect"
"strings"
)
// ContentTypeHandler is a middleware for handling incoming and outgoing
// Content-Types. Incoming Content-Types that are not JSON are rejected.
// Outgoing resposnes are given an application/json Content-Type. This
// middleware automatically prepends routes added to Bourbon.
func ContentTypeHandler(rw http.ResponseWriter, r *http.Request) (int, Encodeable) {
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
contentType := strings.Split(r.Header.Get("Content-Type"), ";")[0]
size := len(contentType)
if size == 0 || (size > 4 && contentType[size-4:] == "json") {
return 0, nil
}
err := fmt.Sprintf("%q is not a supported Content-Type", contentType)
message := CreateMessage(415, err)
return 415, message
}
// DecodeHandler is a middleware for decoding JSON request bodies into structs.
// The middleware will analyze the argument list of the route's Handler to
// determine if the request body should be decoded. If the argument list
// contains a struct type that does not belong to the net/http or bourbon
// package, DecodeHandler assumes the request body should be decoded into a
// value of that type and passed into the route's Handler.
func DecodeHandler(c *context, r *http.Request) (int, Encodeable) {
if r.ContentLength == 0 {
return 0, nil
}
typeOf := reflect.TypeOf(c.handler)
for i := 0; i < typeOf.NumIn(); i++ {
argument := typeOf.In(i)
if value := c.Get(argument); value.IsValid() {
continue
}
value := reflect.New(argument)
err := json.NewDecoder(r.Body).Decode(value.Interface())
if err != nil {
message := CreateMessage(400, err.Error())
return 400, message
}
c.Map(reflect.Indirect(value).Interface())
break
}
return 0, nil
}