/
data.go
81 lines (66 loc) · 2.01 KB
/
data.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
79
80
81
package gohttp
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"os"
"strings"
"github.com/ajg/form"
)
//------------------------------------------------------------------------------
// JSON Data
//------------------------------------------------------------------------------
// JSONData serializes an interface{} of JSON and converts to an `io.Reader`.
func JSONData(values interface{}) (io.Reader, error) {
if values == nil {
return nil, nil
}
jsonData, err := json.Marshal(values)
if err != nil {
return nil, err
}
buffer := bytes.NewBuffer(jsonData)
return buffer, nil
}
// ParseJSON parses the JSON data from an `io.Reader` into an `interface{}`.
// This method utilizes the `UserNumber` feature of the `json.Decoder` which
// causes the Decoder to unmarshal a number into an interface{} as a Number
// instead of as a float64.
func ParseJSON(data io.Reader) (interface{}, error) {
decoder := json.NewDecoder(data)
decoder.UseNumber()
var json interface{}
err := decoder.Decode(&json)
if err != nil {
return nil, err
}
return json, nil
}
//------------------------------------------------------------------------------
// Form Data
//------------------------------------------------------------------------------
// FormData ecodes from data from an interface{} and converts to an `io.Reader`.
func FormData(data interface{}) (io.Reader, error) {
values, err := form.EncodeToValues(data)
if err != nil {
return nil, err
}
body := bytes.NewBufferString(values.Encode())
return body, nil
}
//------------------------------------------------------------------------------
// Pretty Print Data
//------------------------------------------------------------------------------
// PrettyPrint prints a JSON representation in a pretty printed manner.
func PrettyPrint(item interface{}) {
b, err := json.Marshal(item)
if err != nil {
log.Fatal(err)
}
var out bytes.Buffer
json.Indent(&out, b, "", "\t")
strBuff := out.String()
fmt.Printf("[%v] - %s\n", strings.ToUpper(os.Getenv("ENV")), strBuff)
}