-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson.go
61 lines (51 loc) · 1.1 KB
/
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
55
56
57
58
59
60
61
package main
import (
"encoding/json"
"io"
"io/ioutil"
)
// Result is returned from many JSON requests.
type Result struct {
Status string `json:"status,omitempty"`
StatusCode int `json:"statuscode"`
Token string `json:"token,omitempty"`
}
// SetStatus fills in the status text from a code.
func (r *Result) SetStatus(code int) {
s, ok := messages[code]
if !ok {
r.StatusCode = StatusOK
r.Status = messages[StatusOK]
return
}
r.StatusCode = code
r.Status = s
}
func respond(w io.Writer, r interface{}) error {
res, err := json.Marshal(r)
if err != nil {
return err
}
_, err = w.Write(res)
if err != nil {
return err
}
return nil
}
// LoadJSON loads a JSON file into a structure.
func LoadJSON(fn string, out interface{}) error {
data, err := ioutil.ReadFile(fn)
if err != nil {
return err
}
return json.Unmarshal(data, out)
}
// SaveJSON writes any structure to file as JSON.
func SaveJSON(fn string, data interface{}) error {
var out []byte
out, err := json.MarshalIndent(data, "\t", "")
if err != nil {
return err
}
return ioutil.WriteFile(fn, out, 0600)
}