-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbody-parser.go
88 lines (74 loc) · 1.79 KB
/
body-parser.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
package artichoke
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
)
type Body struct {
Data interface{}
Raw []byte
Err error
}
func NewBody(d interface{}, r []byte, e error) *Body {
body := new(Body)
body.Data = d
body.Raw = r
body.Err = e
return body
}
func GetBody(d Data) *Body {
if b, ok := d.Get("body"); ok {
return b.(*Body)
}
return nil
}
func BodyParser(maxMemory int64) Middleware {
return func(w http.ResponseWriter, r *http.Request, d Data) bool {
// ignore GET and HEAD requests, they don't have useful data
if r.Method != "PUT" && r.Method != "POST" {
return false
}
s := r.Header.Get("Content-Type")
switch {
// parse as JSON
case strings.Contains(s, "application/json"):
s, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Println("Error reading body: " + err.Error())
return false
}
var body interface{}
err = json.Unmarshal(s, &body)
if err != nil {
fmt.Println("Error parsing JSON: " + err.Error())
}
d.Set("body", NewBody(body, s, err))
case strings.Contains(s, "multipart/form-data"):
err := r.ParseMultipartForm(maxMemory)
if err != nil {
fmt.Println("Error parsing body as multi-part form: " + err.Error())
}
d.Set("body", NewBody("", nil, err))
case strings.Contains(s, "application/x-www-form-encoded"):
err := r.ParseForm()
if err != nil {
fmt.Println("Error parsing body as form")
}
d.Set("body", NewBody("", nil, err))
// treat as default handler
case strings.Contains(s, "text/plain"):
fallthrough
// last resort, just read the body and pass it
default:
s, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Println("Error reading body: " + err.Error())
return false
}
d.Set("body", NewBody(string(s), s, err))
}
return false
}
}