/
http_response.go
55 lines (49 loc) · 1.21 KB
/
http_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
44
45
46
47
48
49
50
51
52
53
54
55
package util
import (
"encoding/json"
"net/http"
"reflect"
)
func isSlice(v interface{}) bool {
return reflect.TypeOf(v).Kind() == reflect.Slice
}
func sliceLen(v interface{}) int {
return reflect.ValueOf(v).Len()
}
func JsonResponse(w http.ResponseWriter, statusCode int, data any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
if data == nil {
w.Write([]byte("{}"))
return
}
responseData := map[string]any{
"status_code": statusCode,
"data": data,
}
if isSlice(data) {
responseData["count"] = sliceLen(data)
}
value, err := json.Marshal(responseData)
if err != nil {
JsonError(w, http.StatusInternalServerError, "Error marshalling response data")
} else {
w.Write(value)
}
}
func JsonError[T any](w http.ResponseWriter, statusCode int, message T) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
json.NewEncoder(w).Encode(map[string]any{
"error": message,
"status": statusCode,
})
}
func JsonErrors[T any](w http.ResponseWriter, statusCode int, message []T) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
json.NewEncoder(w).Encode(map[string]any{
"errors": message,
"status": statusCode,
})
}