-
Notifications
You must be signed in to change notification settings - Fork 438
/
utils.go
37 lines (32 loc) · 783 Bytes
/
utils.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
package servers
import (
"encoding/json"
"net/http"
)
const (
contentType = "Content-Type"
contentTypeJSON = "application/json"
)
func writeMsg(w http.ResponseWriter, code int, msg string) {
w.WriteHeader(code)
_, _ = w.Write([]byte(msg))
}
func writeJSON(w http.ResponseWriter, obj interface{}) {
b, err := json.Marshal(obj)
if err != nil {
writeMsg(w, http.StatusInternalServerError, err.Error())
return
}
w.Header().Set(contentType, contentTypeJSON)
_, _ = w.Write(b)
}
func writeJsonWithStatusCode(w http.ResponseWriter, code int, obj interface{}) {
b, err := json.Marshal(obj)
if err != nil {
writeMsg(w, http.StatusInternalServerError, err.Error())
return
}
w.WriteHeader(code)
w.Header().Set(contentType, contentTypeJSON)
_, _ = w.Write(b)
}