-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsender.go
More file actions
44 lines (38 loc) · 1.09 KB
/
sender.go
File metadata and controls
44 lines (38 loc) · 1.09 KB
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
package chiweb
import (
"github.com/bytedance/sonic"
"log/slog"
"net/http"
)
func SendJSON(w http.ResponseWriter, statusCode int, data []byte) (int, error) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
return w.Write(data)
}
func SendTEXT(w http.ResponseWriter, statusCode int, data []byte) (int, error) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(statusCode)
return w.Write(data)
}
func SendJSONObjectOK(w http.ResponseWriter, data any) {
SendJSONObject(w, http.StatusOK, data)
}
func SendJSONObject(w http.ResponseWriter, statusCode int, data any) {
bytes, err := sonic.ConfigFastest.Marshal(map[string]any{
"status": "success",
"data": data,
})
if err != nil {
slog.Error("app: failed to marshal data: %v", err)
SendERROR(w, http.StatusInternalServerError, "data serialized error")
} else {
SendJSON(w, statusCode, bytes)
}
}
func SendERROR(w http.ResponseWriter, statusCode int, msg string) {
bytes, _ := sonic.ConfigFastest.Marshal(map[string]any{
"status": "error",
"msg": msg,
})
SendJSON(w, statusCode, bytes)
}