-
Notifications
You must be signed in to change notification settings - Fork 5
/
request.go
72 lines (57 loc) · 1.68 KB
/
request.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
package don
import (
"reflect"
"github.com/abemedia/go-don/decoder"
"github.com/abemedia/go-don/encoding"
"github.com/abemedia/httprouter"
"github.com/valyala/fasthttp"
)
type requestDecoder[V any] func(v *V, ctx *fasthttp.RequestCtx, p httprouter.Params) error
func newRequestDecoder[V any](v V) requestDecoder[V] {
path, _ := decoder.NewCached(v, "path")
query, _ := decoder.NewCached(v, "query")
header, _ := decoder.NewCached(v, "header")
if path == nil && query == nil && header == nil {
return decodeBody[V]()
}
return decodeRequest(path, query, header)
}
func decodeRequest[V any](path, query, header *decoder.CachedDecoder[V]) requestDecoder[V] {
body := decodeBody[V]()
return func(v *V, ctx *fasthttp.RequestCtx, p httprouter.Params) error {
if err := body(v, ctx, nil); err != nil {
return err
}
val := reflect.ValueOf(v).Elem()
if path != nil && len(p) > 0 {
if err := path.DecodeValue((decoder.Params)(p), val); err != nil {
return ErrNotFound
}
}
if query != nil {
if q := ctx.Request.URI().QueryArgs(); q.Len() > 0 {
if err := query.DecodeValue((*decoder.Args)(q), val); err != nil {
return err
}
}
}
if header != nil {
if err := header.DecodeValue((*decoder.Header)(&ctx.Request.Header), val); err != nil {
return err
}
}
return nil
}
}
func decodeBody[V any]() requestDecoder[V] {
return func(v *V, ctx *fasthttp.RequestCtx, _ httprouter.Params) error {
if ctx.Request.Header.ContentLength() == 0 || ctx.IsGet() || ctx.IsHead() {
return nil
}
dec := encoding.GetDecoder(getMediaType(ctx.Request.Header.ContentType()))
if dec == nil {
return ErrUnsupportedMediaType
}
return dec(ctx, v)
}
}