-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathresponses.go
47 lines (37 loc) · 1.32 KB
/
responses.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
package webh
import (
"encoding/json"
"net/http"
)
// Response is a wrapper for web handlers that are compliant with the stdlib.
func Response(status int, w http.ResponseWriter, msg string, data any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(HttpResponse{
Message: msg,
Data: data,
Success: status < 399,
})
}
// Res is a wrapper for web handlers that are compliant with the stdlib signature but returning an error.
func Res(status int, w http.ResponseWriter, data any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(data)
}
// ResErr is a wrapper for web handlers that are compliant with the stdlib signature but returning an error.
func ResErr(status int, w http.ResponseWriter, data any) error {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
return json.NewEncoder(w).Encode(data)
}
// ResponseErr is a wrapper for web handlers that are compliant with the stdlib signature but returning an error.
func ResponseErr(status int, w http.ResponseWriter, msg string, data any) error {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
return json.NewEncoder(w).Encode(HttpResponse{
Message: msg,
Data: data,
Success: status < 399,
})
}