-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponse.go
43 lines (40 loc) · 992 Bytes
/
response.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
package bec_http
import (
"encoding/json"
"net/http"
)
func SendErrText(w http.ResponseWriter, err error) {
status := http.StatusInternalServerError
if e, ok := err.(*StatusError); ok {
status = e.Status()
}
http.Error(w, err.Error(), status)
}
func SendResText(w http.ResponseWriter, res string) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(res))
}
func SendResBytes(w http.ResponseWriter, bytes []byte) {
w.WriteHeader(http.StatusOK)
w.Write(bytes)
}
func SendErr(w http.ResponseWriter, err error) {
status := http.StatusInternalServerError
if e, ok := err.(IStatusError); ok {
status = e.Status()
}
w.WriteHeader(status)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{
"status": status,
"error": err.Error(),
})
}
func SendRes(w http.ResponseWriter, res any) {
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
if res == nil {
res = EmptyRes
}
json.NewEncoder(w).Encode(res)
}