-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_param.go
62 lines (50 loc) · 1.17 KB
/
http_param.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
package do
import (
"context"
"net/url"
)
type ParamParser[T ParamData] struct {
decoder Decoder[T]
}
func NewParamParser[T ParamData](decoder Decoder[T]) *ParamParser[T] {
paramParser := &ParamParser[T]{
decoder: decoder,
}
return paramParser
}
type ParamData interface {
url.Values | []byte
}
type Decoder[T ParamData] interface {
Decode(src T, v any) error
}
type DecodeFunc[T ParamData] func(src T, v any) error
func (f DecodeFunc[T]) Decode(src T, v any) error {
return f(src, v)
}
// Parse parse data to v with decoder.
func (p *ParamParser[T]) Parse(data T, v any) error {
err := p.decoder.Decode(data, v)
if err != nil {
return err
}
return nil
}
// ParseAndCheck parse data to v with decoder and check v if v implement interface{ Check(context.Context) error } or interface{ Check() error }.
func (p *ParamParser[T]) ParseAndCheck(ctx context.Context, data T, v any) error {
if err := p.Parse(data, v); err != nil {
return err
}
// check param
var err error
switch vv := v.(type) {
case interface{ Check(context.Context) error }:
err = vv.Check(ctx)
case interface{ Check() error }:
err = vv.Check()
}
if err != nil {
return err
}
return nil
}