This repository was archived by the owner on Jul 6, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathRequestBody.go
78 lines (58 loc) · 1.42 KB
/
RequestBody.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
package aero
import (
"encoding/json"
"io"
"io/ioutil"
"github.com/akyoto/stringutils/unsafe"
)
// RequestBody represents a request body.
type RequestBody struct {
reader io.ReadCloser
}
// Reader returns an io.Reader for the request body.
func (body RequestBody) Reader() io.ReadCloser {
return body.reader
}
// JSON parses the body as a JSON object.
func (body RequestBody) JSON() (interface{}, error) {
if body.reader == nil {
return nil, ErrEmptyBody
}
decoder := json.NewDecoder(body.reader)
defer body.reader.Close()
var data interface{}
err := decoder.Decode(&data)
if err != nil {
return nil, err
}
return data, nil
}
// JSONObject parses the body as a JSON object and returns a map[string]interface{}.
func (body RequestBody) JSONObject() (map[string]interface{}, error) {
json, err := body.JSON()
if err != nil {
return nil, err
}
data, ok := json.(map[string]interface{})
if !ok {
return nil, ErrExpectedJSONObject
}
return data, nil
}
// Bytes returns a slice of bytes containing the request body.
func (body RequestBody) Bytes() ([]byte, error) {
data, err := ioutil.ReadAll(body.reader)
defer body.reader.Close()
if err != nil {
return nil, err
}
return data, nil
}
// String returns a string containing the request body.
func (body RequestBody) String() (string, error) {
bytes, err := body.Bytes()
if err != nil {
return "", err
}
return unsafe.BytesToString(bytes), nil
}