-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.go
40 lines (36 loc) · 944 Bytes
/
helpers.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
package heligo
import (
"encoding/json"
"net/http"
)
// bodyAllowedForStatus is a copy of http.bodyAllowedForStatus non-exported function.
func bodyAllowedForStatus(status int) bool {
switch {
case status >= 100 && status <= 199:
return false
case status == http.StatusNoContent:
return false
case status == http.StatusNotModified:
return false
}
return true
}
// WriteJSON writes a JSON body with the appropriate header.
func WriteJSON(w http.ResponseWriter, status int, obj any) (int, error) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
if !bodyAllowedForStatus(status) {
return status, nil
}
jsonBytes, err := json.Marshal(obj)
if err != nil {
return status, err
}
_, err = w.Write(jsonBytes)
return status, err
}
// WriteHeader is just for convenience
func WriteHeader(w http.ResponseWriter, status int) (int, error) {
w.WriteHeader(status)
return status, nil
}