-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlerdata.go
415 lines (384 loc) · 10.9 KB
/
handlerdata.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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
package eudore
import (
"encoding/json"
"encoding/xml"
"fmt"
"html/template"
"io/fs"
"net/http"
"os"
"path/filepath"
"reflect"
"strings"
)
// HandlerDataFunc defines the [Context] data processing function.
//
// Define behaviors such as Bind and Render.
//
// Bind is used to request data parsing.
// By default, [HeaderContentType] is used to select the data parsing method.
//
// Render is used to return response data.
// By default, [HeaderAccept] is used to select the data rendering method.
type HandlerDataFunc = func(Context, any) error
// The NewHandlerDataFuncs function combines multiple [HandlerDataFunc] to
// process data in sequence.
func NewHandlerDataFuncs(handlers ...HandlerDataFunc) HandlerDataFunc {
switch len(handlers) {
case 0:
return nil
case 1:
return handlers[0]
default:
return func(ctx Context, data any) error {
for i := range handlers {
err := handlers[i](ctx, data)
if err != nil {
return err
}
}
return nil
}
}
}
// NewHandlerDataStatusCode function wraps the response status or code
// when [HandlerDataFunc] returns an error.
//
// If err is [http.MaxBytesError],
// it may override [StatusRequestEntityTooLarge].
func NewHandlerDataStatusCode(handler HandlerDataFunc, status, code int,
) HandlerDataFunc {
if handler == nil || (status == 0 && code == 0) {
return handler
}
return func(ctx Context, data any) error {
err := handler(ctx, data)
if err != nil {
return NewErrorWithStatusCode(err, status, code)
}
return nil
}
}
// The NewHandlerDataBinds method defines the [HeaderContentType] mapping
// Bind function.
//
// [DefaultHandlerDataBinds] is used by default.
// [HandlerDataBindURL] is used when [HeaderContentType] is empty.
//
// If there is no matching [HandlerDataFunc],
// return [StatusUnsupportedMediaType].
func NewHandlerDataBinds(binds map[string]HandlerDataFunc) HandlerDataFunc {
if binds == nil {
binds = mapClone(DefaultHandlerDataBinds)
}
if _, ok := binds[""]; !ok {
binds[""] = HandlerDataBindURL
}
var mimes string
for k := range binds {
if k != "" && k != MimeApplicationOctetStream {
mimes += ", " + k
}
}
mimes = strings.TrimPrefix(mimes, ", ")
return func(ctx Context, data any) error {
contentType := ctx.GetHeader(HeaderContentType)
fn, ok := binds[strings.SplitN(contentType, ";", 2)[0]]
if ok {
return fn(ctx, data)
}
switch ctx.Method() {
case MethodPost:
ctx.SetHeader(HeaderAcceptPost, mimes)
case MethodPatch:
ctx.SetHeader(HeaderAcceptPatch, mimes)
}
err := fmt.Errorf(ErrHandlerDataBindNotSupportContentType, contentType)
return NewErrorWithStatus(err, StatusUnsupportedMediaType)
}
}
func bindMaps[T any](source map[string][]T, target any, tags []string) error {
v := reflect.Indirect(reflect.ValueOf(target))
switch v.Kind() {
case reflect.Struct, reflect.Map:
for key, vals := range source {
for _, val := range vals {
err := SetAnyByPathWithTag(target, key, val, tags, false)
// need to be improved
if err != nil &&
!strings.Contains(err.Error(), "not found field ") {
return err
}
}
}
return nil
default:
// map data is unordered and cannot be bound to an array.
return fmt.Errorf(ErrHandlerDataBindMustSturct,
reflect.TypeOf(target).String(),
)
}
}
// The HandlerDataBindURL function uses the url parameter to Bind data.
//
// Using tag [DefaultHandlerDataBindURLTags],
// Use the [SetAnyByPathWithTag] function to bind data.
func HandlerDataBindURL(ctx Context, data any) error {
vals, err := ctx.Querys()
if err != nil {
return err
}
if len(vals) > 0 {
return bindMaps(vals, data, DefaultHandlerDataBindURLTags)
}
return nil
}
// The HandlerDataBindForm function uses form data to Bind data.
//
// If the request body is empty, use the url parameter.
//
// Using tag [DefaultHandlerDataBindFormTags],
// Use the [SetAnyByPathWithTag] function to bind data.
func HandlerDataBindForm(ctx Context, data any) error {
vals, err := ctx.FormValues()
if err != nil {
return err
}
files := ctx.FormFiles()
if len(files) > 0 {
_ = bindMaps(files, data, DefaultHandlerDataBindFormTags)
}
if len(vals) > 0 {
return bindMaps(vals, data, DefaultHandlerDataBindFormTags)
}
return nil
}
// The HandlerDataBindJSON function uses [json.NewDecoder] to Bind data.
func HandlerDataBindJSON(ctx Context, data any) error {
return json.NewDecoder(ctx).Decode(data)
}
// The BindXML function uses [xml.NewDecoder] to Bind data.
func HandlerDataBindXML(ctx Context, data any) error {
return xml.NewDecoder(ctx).Decode(data)
}
// The HandlerDataBindProtobuf function uses the built-in [NewProtobufDecoder]
// to Bind protobuf data.
func HandlerDataBindProtobuf(ctx Context, data any) error {
return NewProtobufDecoder(ctx).Decode(data)
}
// The NewHandlerDataRenders method uses [HeaderAccept] to matching for
// Render functions in renders.
// [DefaultHandlerDataRenders] is used by default.
//
// If Render fails and [ResponseWriter].Size=0, ignore this Render.
func NewHandlerDataRenders(renders map[string]HandlerDataFunc) HandlerDataFunc {
if renders == nil {
renders = mapClone(DefaultHandlerDataRenders)
}
render, ok := renders[MimeAll]
if !ok {
render = DefaultHandlerDataRenderFunc
}
return func(ctx Context, data any) error {
w := ctx.Response()
h := w.Header()
contentType, vary := h[HeaderContentType], h[HeaderVary]
for _, accept := range strings.Split(ctx.GetHeader(HeaderAccept), ",") {
name, quality, ok := strings.Cut(strings.TrimSpace(accept), ";")
if ok && quality == "q=0" {
continue
}
fn, ok := renders[name]
if ok && fn != nil {
h.Set(HeaderVary,
strings.Join(append(vary, HeaderAccept), ", "),
)
err := fn(ctx, data)
// Render is successful if return nil
// Render is irrevocable if size > 0
if err == nil || w.Size() > 0 {
return err
}
h[HeaderContentType], h[HeaderVary] = contentType, vary
}
}
return render(ctx, data)
}
}
func renderSetContentType(ctx Context, mime string) {
h := ctx.Response().Header()
if val := h.Get(HeaderContentType); len(val) == 0 {
h.Add(HeaderContentType, mime)
}
}
// RenderText function Render Text, written using the [fmt.Fprint] function.
func HandlerDataRenderText(ctx Context, data any) error {
renderSetContentType(ctx, MimeTextPlainCharsetUtf8)
var err error
switch v := data.(type) {
case []byte:
_, err = ctx.Write(v)
case string:
_, err = ctx.WriteString(v)
case fmt.Stringer:
_, err = ctx.WriteString(v.String())
default:
_, err = fmt.Fprintf(ctx, "%#v", data)
}
return err
}
// The HandlerDataRenderJSON function uses [json.NewEncoder] to Render data.
//
// If [HeaderAccept] is not [MimeApplicationJSON], use json indent for output.
func HandlerDataRenderJSON(ctx Context, data any) error {
renderSetContentType(ctx, MimeApplicationJSONCharsetUtf8)
switch reflect.Indirect(reflect.ValueOf(data)).Kind() {
case reflect.Struct, reflect.Map, reflect.Slice, reflect.Array:
default:
data = NewContextMessgae(ctx, nil, data)
}
encoder := json.NewEncoder(ctx)
if !strings.Contains(ctx.GetHeader(HeaderAccept), MimeApplicationJSON) {
encoder.SetIndent("", "\t")
}
return encoder.Encode(data)
}
// The HandlerDataRenderProtobuf function uses the built-in [NewProtobufEncoder]
// to Render protobuf data.
// Invalid properties will be ignored.
func HandlerDataRenderProtobuf(ctx Context, data any) error {
renderSetContentType(ctx, MimeApplicationProtobuf)
return NewProtobufEncoder(ctx).Encode(data)
}
// The HandlerDataRenderHTML function creates Render using [template.Template].
//
// patterns will load templates from both [template.ParseFS] and
// [template.ParseFiles].
//
// If [fs.FS] is not empty, the [embed] template will be loaded.
//
// If patterns loads the template from the [os]; each request is reloaded,
// you can use [DefaultHandlerDataTemplateReload] to
// turn off the template automatic reload feature.
//
// When returning an HTML response,
// append [DefaultHandlerDataRenderTemplateHeaders].
//
// If go run is started, workdir may be in a temp directory and the file cannot
// be read.
func NewHandlerDataRenderTemplates(temp *template.Template,
fs fs.FS, patterns ...string,
) HandlerDataFunc {
if temp == nil {
temp = template.New("")
}
t, reload, err := parseTemplates(temp, fs, patterns)
if err != nil {
return func(ctx Context, _ any) error {
return renderTemplatesError(ctx, err)
}
}
h := templateHeaders()
if reload && DefaultHandlerDataTemplateReload {
return func(ctx Context, data any) error {
t, _, err := parseTemplates(temp, nil, patterns)
if err != nil {
return renderTemplatesError(ctx, err)
}
return renderTemplatesData(ctx, data, t, h)
}
}
return func(ctx Context, data any) error {
return renderTemplatesData(ctx, data, t, h)
}
}
func templateHeaders() http.Header {
h := make(http.Header)
h[HeaderContentType] = []string{MimeTextHTMLCharsetUtf8}
for k, v := range DefaultHandlerDataRenderTemplateHeaders {
h.Set(k, v)
}
return h
}
func parseTemplates(temp *template.Template, fs fs.FS, patterns []string,
) (*template.Template, bool, error) {
temp, err := temp.Clone()
if err != nil {
return nil, false, err
}
size0 := len(temp.Templates())
if fs != nil && len(patterns) > 0 {
_, err := temp.ParseFS(fs, patterns...)
if err != nil {
return nil, false, err
}
}
size1 := len(temp.Templates())
for i := range patterns {
names, err := filepath.Glob(patterns[i])
if err != nil {
return nil, false, err
}
if len(names) > 0 {
_, err = temp.ParseFiles(names...)
if err != nil {
return nil, false, err
}
}
}
size2 := len(temp.Templates())
if patterns != nil && size0 == size2 {
dir, _ := os.Getwd()
return nil, false, fmt.Errorf(ErrHandlerDataRenderTemplateNotLoad,
dir, patterns,
)
}
// append default template
for _, t := range DefaultHandlerDataRenderTemplateAppend.Templates() {
if temp.Lookup(t.Name()) == nil {
_, _ = temp.AddParseTree(t.Name(), t.Tree)
}
}
return temp, size1 != size2, nil
}
func renderTemplatesError(ctx Context, err error) error {
ctx.Error(err)
renderSetContentType(ctx, MimeTextPlainCharsetUtf8)
ctx.WriteHeader(StatusInternalServerError)
_, _ = ctx.WriteString(err.Error())
return nil
}
func renderTemplatesData(ctx Context, data any,
temp *template.Template, hr http.Header,
) error {
name := ctx.GetParam(ParamTemplate)
if name == "" {
var err error
switch v := data.(type) {
case []byte:
renderSetContentType(ctx, MimeTextPlainCharsetUtf8)
_, err = ctx.Write(v)
case string:
renderSetContentType(ctx, MimeTextPlainCharsetUtf8)
_, err = ctx.WriteString(v)
case fmt.Stringer:
renderSetContentType(ctx, MimeTextPlainCharsetUtf8)
_, err = ctx.WriteString(v.String())
default:
return ErrHandlerDataRenderTemplateNeedName
}
return err
}
t := temp.Lookup(name)
if t == nil {
return fmt.Errorf(ErrHandlerDataRenderTemplateNotFound, name)
}
hw := ctx.Response().Header()
for k, v := range hr {
if hw.Values(k) == nil {
hw[k] = v
}
}
_ = t.Execute(ctx, data)
return nil
}