/
getter_body.go
42 lines (34 loc) · 1.08 KB
/
getter_body.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
package domain
import (
"net/http"
"github.com/pkg/errors"
"github.com/tidwall/gjson"
)
// BodyGetter defines the behavior or something that can
// extract information from a response body.
type BodyGetter interface {
Get(path string, body []byte) (value string, err error)
}
// NewBodyGetter returns the body extracter based on the
// Content-Type found in the response headers.
func NewBodyGetter(resp *http.Response) (e BodyGetter, err error) {
contentType := resp.Header.Get("Content-Type")
switch contentType {
case "application/json":
return &JSONBodyGetter{}, nil
default:
return nil, errors.Errorf("invalid Content-Type %q", contentType)
}
}
// JSONBodyGetter extracts information from a response
// body using JSON dot notation.
type JSONBodyGetter struct{}
// Get extracts a value out of a JSON body using JSON
// dot notation.
func (e *JSONBodyGetter) Get(path string, body []byte) (value string, err error) {
result := gjson.GetBytes(body, path)
if !result.Exists() {
return "", errors.Errorf("no value at path %q in JSON body", path)
}
return result.String(), nil
}