-
Notifications
You must be signed in to change notification settings - Fork 0
/
helper.go
45 lines (38 loc) · 915 Bytes
/
helper.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
package main
import (
"encoding/json"
"net/http"
)
func permissionDenied(w http.ResponseWriter) {
writeJson(w, http.StatusBadRequest, ApiError{
Error: "Invalid token",
})
}
type ApiFunc func(http.ResponseWriter, *http.Request) error
type ApiError struct {
Error string `json:"error"`
}
func MakeHttpHandlerFunc(A ApiFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
if err := A(w, req); err != nil {
writeJson(w, http.StatusBadRequest, ApiError{
Error: err.Error(),
})
}
}
}
type ApiServer struct {
listenAddress string
store Storage
}
func writeJson(w http.ResponseWriter, status int, v any) error {
w.WriteHeader(status)
w.Header().Add("Content-Type", "application/json")
return json.NewEncoder(w).Encode(v)
}
func newApiServer(las string, store Storage) *ApiServer {
return &ApiServer{
listenAddress: las,
store: store,
}
}