-
Notifications
You must be signed in to change notification settings - Fork 0
/
tools.go
86 lines (66 loc) · 1.71 KB
/
tools.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
82
83
84
85
86
package jsontools
import (
"encoding/json"
"errors"
"io"
"net/http"
)
type Tools struct {
MaxFileSize int
}
// JSONResponse is the type used for sending JSON around
type JsonResponse struct {
Error bool `json:"error"`
Message string `json:"message"`
Port string `json:"port,omitempty"`
Data any `json:"data,omitempty"`
}
// Tries to read the body of a request and converts it into JSON
func (t *Tools) ReadJSON(w http.ResponseWriter, r *http.Request, data any) error {
maxBytes := 1048576 // one megabyte
if t.MaxFileSize > 0 {
maxBytes = t.MaxFileSize
}
r.Body = http.MaxBytesReader(w, r.Body, int64(maxBytes))
dec := json.NewDecoder(r.Body)
err := dec.Decode(data)
if err != nil {
return err
}
err = dec.Decode(&struct{}{})
if err != io.EOF {
return errors.New("body must have only a single JSON value")
}
return nil
}
// Takes a response status code and arbitrary data and writes a json response to the client
func (t *Tools) WriteJSON(w http.ResponseWriter, status int, data any, 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(status)
_, err = w.Write(out)
if err != nil {
return err
}
return nil
}
// takes an error, and optionally a response status code, and generates and sends json
func (t *Tools) ErrorJSON(w http.ResponseWriter, err error, status ...int) error {
statusCode := http.StatusBadRequest
if len(status) > 0 {
statusCode = status[0]
}
payload := JsonResponse{
Error: true,
Message: err.Error(),
}
return t.WriteJSON(w, statusCode, payload)
}