-
Notifications
You must be signed in to change notification settings - Fork 20
/
querier.go
67 lines (57 loc) · 1.23 KB
/
querier.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
package requestbodyvar
import (
"bytes"
"fmt"
"mime"
"strings"
"github.com/basgys/goxml2json"
"github.com/tidwall/gjson"
)
type Querier interface {
Query(string) string
}
type JSON struct {
buf *bytes.Buffer
}
func (j JSON) Query(key string) string {
return getJSONField(j.buf, key)
}
type XML struct {
buf *bytes.Buffer
}
func (x XML) Query(key string) string {
json, err := xml2json.Convert(x.buf)
if err != nil {
return ""
}
return getJSONField(json, key)
}
func newQuerier(buf *bytes.Buffer, contentType string) (Querier, error) {
mediaType := "application/json"
if contentType != "" {
var err error
mediaType, _, err = mime.ParseMediaType(contentType)
if err != nil {
return nil, err
}
}
switch {
case mediaType == "application/json":
return JSON{buf: buf}, nil
case strings.HasSuffix(mediaType, "/xml"):
// application/xml
// text/xml
return XML{buf: buf}, nil
default:
return nil, fmt.Errorf("unsupported Media Type: %q", mediaType)
}
}
// getJSONField gets the value of the given field from the JSON body,
// which is buffered in buf.
func getJSONField(buf *bytes.Buffer, key string) string {
if buf == nil {
return ""
}
value := gjson.GetBytes(buf.Bytes(), key)
return value.String()
}