-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
223 lines (189 loc) · 4.68 KB
/
handler.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
package japi
import (
"context"
"net/http"
"github.com/goccy/go-json"
"github.com/jarrettv/go-japi/decoder"
"github.com/jarrettv/go-japi/problem"
"github.com/julienschmidt/httprouter"
)
// StatusCoder allows you to customise the HTTP response code.
type StatusCoder interface {
StatusCode() int
}
// Headerer allows you to customise the HTTP headers.
type Headerer interface {
Header() http.Header
}
// Problemer allows you to customize the error problem details.
type Problemer interface {
Problem() problem.Problem
}
// Handler allows you to handle request with the route params
type Handler interface {
http.Handler
handle(http.ResponseWriter, *http.Request, httprouter.Params)
}
// H wraps your handler function with the Go generics magic.
func H[T any, O any](handle Handle[T, O]) Handler {
h := &handler[T, O]{handler: handle}
var t T
if hasTag(t, headerTag) {
dec, err := decoder.NewCachedDecoder(t, headerTag)
if err == nil {
h.decodeHeader = dec
}
}
if hasTag(t, queryTag) {
dec, err := decoder.NewMapDecoder(t, queryTag)
if err == nil {
h.decodeQuery = dec
}
}
if hasTag(t, pathTag) {
dec, err := decoder.NewParamsDecoder(t, pathTag)
if err == nil {
h.decodePath = dec
}
}
return h
}
// E creates a Handler that returns the error
func E(err error) Handler {
return H(func(context.Context, *Empty) (*Empty, error) {
return nil, err
})
}
// LoadRawJson loads raw json to response useful for swagger docs.
func LoadRawJson(loadRawJson func() ([]byte, error)) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
json, e := loadRawJson()
if e != nil {
http.Error(w, e.Error(), http.StatusInternalServerError)
return
}
RawJson(json)
})
}
// RawJson sends raw json to response useful for swagger docs.
func RawJson(data []byte) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, e := w.Write(data)
if e != nil {
http.Error(w, e.Error(), http.StatusInternalServerError)
}
})
}
// Handle is the type for your handlers.
type Handle[T any, O any] func(ctx context.Context, request T) (O, error)
type handler[T any, O any] struct {
config *Config
handler Handle[T, O]
decodeHeader *decoder.CachedDecoder
decodePath *decoder.ParamsDecoder
decodeQuery *decoder.MapDecoder
isNil func(v any) bool
}
func (h *handler[T, O]) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.handle(w, r, nil)
}
//nolint:gocognit,cyclop
func (h *handler[T, O]) handle(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
if h.config.RouteLogFunc != nil {
route := p.MatchedRoutePath()
vars := make(map[string]string, len(p))
for _, param := range p {
if param.Value != route {
vars[param.Key] = param.Value
}
}
h.config.RouteLogFunc(r.Context(), route, vars) // TODO (jv) get route
}
serveProblem := func(p *problem.Problem) {
h.config.Enrich(r.Context(), p)
if h.config.ProblemLogFunc != nil {
h.config.ProblemLogFunc(r.Context(), p)
}
p.ServeJSON(w)
}
serveRequestProblem := func(e error) {
p := problem.BadRequest(e)
serveProblem(p)
}
req := new(T)
// Decode the header
if h.decodeHeader != nil {
e := h.decodeHeader.Decode(r.Header, req)
if e != nil {
serveRequestProblem(e)
return
}
}
// Decode the URL query
if h.decodeQuery != nil && r.URL.RawQuery != "" {
e := h.decodeQuery.Decode(r.URL.Query(), req)
if e != nil {
serveRequestProblem(e)
return
}
}
// Decode the path params
if h.decodePath != nil && len(p) != 0 {
e := h.decodePath.Decode(p, req)
if e != nil {
serveRequestProblem(e)
return
}
}
// Decode the body
if r.ContentLength > 0 {
dec, e := getDecoder(JsonEncoding)
if e != nil {
serveRequestProblem(e) // http.ErrNotSupported
return
}
if e := dec(r, req); e != nil {
serveRequestProblem(e)
return
}
}
var res any
res, e := h.handler(r.Context(), *req)
w.Header().Set("Content-Type", JsonEncoding+"; charset=utf-8")
if e != nil {
if pb, ok := e.(Problemer); ok {
p := pb.Problem()
serveProblem(&p)
return
} else if p, ok := e.(*problem.Problem); ok {
serveProblem(p)
return
} else {
p := problem.Unexpected(e)
serveProblem(p)
return
}
}
if h, ok := res.(Headerer); ok {
headers := w.Header()
for k, v := range h.Header() {
headers[k] = v
}
}
if sc, ok := res.(StatusCoder); ok {
w.WriteHeader(sc.StatusCode())
}
if e = json.NewEncoder(w).Encode(res); e != nil {
p := problem.Unexpected(e)
serveProblem(p)
}
}
func (h *handler[T, O]) setConfig(r *Config) {
h.config = r
}
const (
headerTag = "header"
pathTag = "path"
queryTag = "query"
)