-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathresponse.go
40 lines (33 loc) · 827 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
package cadet
import (
"encoding/json"
"net/http"
)
type Response func(w http.ResponseWriter)
func JSON(response any) Response {
return func(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(w).Encode(response)
}
}
func Text(text string) Response {
return func(w http.ResponseWriter) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Write([]byte(text))
}
}
func Status(status int) Response {
return func(w http.ResponseWriter) {
w.WriteHeader(status)
}
}
func Error(status int, message string) Response {
return func(w http.ResponseWriter) {
type response struct {
Error string `json:"error"`
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
JSON(&response{message})(w)
}
}