forked from Eun/go-hit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_json.go
54 lines (46 loc) · 1.2 KB
/
http_json.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
package hit
import (
"encoding/json"
"github.com/Eun/go-convert"
"github.com/Eun/go-hit/expr"
"github.com/Eun/go-hit/internal/minitest"
)
type HTTPJson struct {
Hit
body *HTTPBody
}
func newHTTPJson(body *HTTPBody) *HTTPJson {
return &HTTPJson{
body: body,
Hit: body.hit,
}
}
// Get returns the body as an interface type based on the underlying data
func (jsn *HTTPJson) Get(expression string) interface{} {
var container interface{}
minitest.NoError(json.NewDecoder(jsn.body.Reader()).Decode(&container))
v, ok, err := expr.GetValue(container, expression, expr.IgnoreCase)
minitest.NoError(err)
if !ok {
v = nil
}
return v
}
// GetAs returns the body as the specified interface type
func (jsn *HTTPJson) GetAs(expression string, container interface{}) interface{} {
var v interface{}
minitest.NoError(json.NewDecoder(jsn.body.Reader()).Decode(&v))
v, ok, err := expr.GetValue(v, expression, expr.IgnoreCase)
minitest.NoError(err)
if !ok {
v = nil
}
minitest.NoError(convert.Convert(v, container))
return container
}
// Set sets the body to the specified json data
func (jsn *HTTPJson) Set(data interface{}) {
buf, err := json.Marshal(data)
minitest.NoError(err)
jsn.body.SetBytes(buf)
}