/
handlers.go
105 lines (89 loc) · 2.49 KB
/
handlers.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
Copyright © 2022 THINKINGATOMS LLC <atom@thinkingatoms.com>
*/
package ez
import (
"encoding/json"
"fmt"
"github.com/rs/zerolog/hlog"
"net/http"
)
func InternalServerErrorHandler(w http.ResponseWriter, r *http.Request, err error) {
_ = r
w.WriteHeader(http.StatusInternalServerError)
_, _ = fmt.Fprintln(w, "internal server error: "+err.Error())
hlog.FromRequest(r).Error().Err(err).Msg("internal server error")
}
func BadRequestHandler(w http.ResponseWriter, r *http.Request, err error) {
_ = r
w.WriteHeader(http.StatusBadRequest)
_, _ = fmt.Fprintln(w, "bad request: "+err.Error())
hlog.FromRequest(r).Error().Err(err).Msg("bad request")
}
func AccessDeniedHandler(w http.ResponseWriter, r *http.Request, err error) {
_ = r
w.WriteHeader(http.StatusUnauthorized)
_, _ = fmt.Fprintln(w, "unauthorized: "+err.Error())
hlog.FromRequest(r).Error().Err(err).Msg("access denied")
}
func ForbiddenHandler(w http.ResponseWriter, r *http.Request, err error) {
_ = r
w.WriteHeader(http.StatusForbidden)
_, _ = fmt.Fprintln(w, "unauthorized: "+err.Error())
hlog.FromRequest(r).Error().Err(err).Msg("forbidden")
}
func NotFoundHandler(w http.ResponseWriter, r *http.Request, err error) {
_ = r
w.WriteHeader(http.StatusNotFound)
_, _ = fmt.Fprintln(w, "unauthorized: "+err.Error())
hlog.FromRequest(r).Error().Err(err).Msg("not found")
}
func WriteObjectAsJSON(w http.ResponseWriter, r *http.Request, v any) {
marshal, err := json.Marshal(v)
if err != nil {
InternalServerErrorHandler(w, r, err)
return
}
_, err = w.Write(marshal)
if err != nil {
InternalServerErrorHandler(w, r, err)
return
}
}
func WriteBytes(w http.ResponseWriter, r *http.Request, marshal []byte) {
_, err := w.Write(marshal)
if err != nil {
InternalServerErrorHandler(w, r, err)
return
}
}
func StaticMsgHandler(msg string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
_ = r
_, _ = w.Write([]byte(msg))
}
}
type DummyResponseWriter struct {
header map[string][]string
StatusCode int
}
func (self *DummyResponseWriter) Header() http.Header {
return self.header
}
func (self *DummyResponseWriter) Write(b []byte) (int, error) {
return len(b), nil
}
func (self *DummyResponseWriter) WriteHeader(statusCode int) {
self.StatusCode = statusCode
}
func GetDummyResponseWriter() *DummyResponseWriter {
return &DummyResponseWriter{
header: make(map[string][]string),
StatusCode: http.StatusOK,
}
}
func _() {
_ = StaticMsgHandler
_ = ForbiddenHandler
_ = NotFoundHandler
}