forked from go-kivik/couchdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
47 lines (43 loc) · 1.03 KB
/
util.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
package couchdb
import (
"bytes"
"encoding/json"
"io"
"strings"
"github.com/flimzy/kivik"
"github.com/flimzy/kivik/errors"
)
// deJSONify unmarshals a string, []byte, or json.RawMessage. All other types
// are returned as-is.
func deJSONify(i interface{}) (interface{}, error) {
var data []byte
switch t := i.(type) {
case string:
data = []byte(t)
case []byte:
data = t
case json.RawMessage:
data = []byte(t)
default:
return i, nil
}
var x interface{}
err := json.Unmarshal(data, &x)
return x, errors.WrapStatus(kivik.StatusBadRequest, err)
}
// toJSON converts a string, []byte, json.RawMessage, or an arbitrary type into
// an io.Reader of JSON marshaled data.
func toJSON(i interface{}) (io.Reader, error) {
switch t := i.(type) {
case string:
return strings.NewReader(t), nil
case []byte:
return bytes.NewReader(t), nil
case json.RawMessage:
return bytes.NewReader(t), nil
default:
buf := &bytes.Buffer{}
err := json.NewEncoder(buf).Encode(i)
return buf, errors.WrapStatus(kivik.StatusBadRequest, err)
}
}