-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
47 lines (37 loc) · 881 Bytes
/
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
package config
import (
"encoding/json"
"errors"
"io"
"net/http"
)
func ReadJSON(w http.ResponseWriter, r *http.Request, data any) error {
maxBytes := 1048576 // one megabyte
r.Body = http.MaxBytesReader(w, r.Body, int64(maxBytes))
dec := json.NewDecoder(r.Body)
if err := dec.Decode(data); err != nil {
return err
}
if err := dec.Decode(&struct{}{}); err != io.EOF {
return errors.New("body must have only a single JSON value")
}
return nil
}
func WriteJSON(w http.ResponseWriter, httpStatus int, data Response, headers ...http.Header) error {
out, err := json.Marshal(data)
if err != nil {
return err
}
if len(headers) > 0 {
for key, value := range headers[0] {
w.Header()[key] = value
}
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(httpStatus)
_, err = w.Write(out)
if err != nil {
return err
}
return nil
}