-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
52 lines (47 loc) · 1.15 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
package snug
import (
"encoding/json"
"log"
"net/http"
)
// Add Content-Type: application/json-header to response.
func AddJsonHeader(rw http.ResponseWriter) {
rw.Header().Add("Content-Type", "application/json")
}
// JSON type enables easy dumping of contents to http.ResponseWriter.
type JSON map[string]any
func (s JSON) dump() ([]byte, error) {
serialized, err := json.Marshal(s)
if err != nil {
log.Printf("ERROR: JSON.Dump: %s", err)
return []byte(`{"error": "internal server error"}`), err
}
return serialized, nil
}
// Write map as a json payload to responsewriter.
//
// Adds content-type header and given status code.
// If serialization fails, returns a status 500 and a message:
//
// {"error": "internal server error"}
//
// Dump some fields to JSON and write to http.ResponseWriter:
//
// func hello(w http.ResponseWriter, r *http.Request) {
// m := snug.JSON{
// "msg": "hello",
// "some": "field",
// "other": 123,
// }
// m.Write(w, 200)
// }
func (s JSON) Write(w http.ResponseWriter, status int) {
AddJsonHeader(w)
res, err := s.dump()
if err != nil {
w.WriteHeader(500)
} else {
w.WriteHeader(status)
}
w.Write(res)
}