-
Notifications
You must be signed in to change notification settings - Fork 0
/
bind.go
112 lines (93 loc) · 1.94 KB
/
bind.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
package espresso
import (
"fmt"
"reflect"
"strings"
)
// BindSource describes the type of bind.
type BindSource int
const (
BindPathParam BindSource = iota
BindFormParam
BindQueryParam
BindHeadParam
)
func (b BindSource) String() string {
switch b {
case BindPathParam:
return "path"
case BindFormParam:
return "form"
case BindQueryParam:
return "query"
case BindHeadParam:
return "head"
}
return fmt.Sprintf("unknown(%d)", int(b))
}
func (b BindSource) Valid() bool {
return !strings.HasPrefix(b.String(), "unknown")
}
type BindFunc func(any, string) error
type BindParam struct {
Key string
From BindSource
Type reflect.Type
Func BindFunc
}
// BindError describes the error when binding a param.
type BindError struct {
Key string
From BindSource
Type reflect.Type
Err error
}
func errorBind(bind BindParam, err error) BindError {
return BindError{
Key: bind.Key,
From: bind.From,
Type: bind.Type,
Err: err,
}
}
func (b BindError) Error() string {
return fmt.Sprintf("bind %s with name %q to type %s error: %v", b.From, b.Key, b.Type, b.Err)
}
func (b BindError) Unwrap() error {
return b.Err
}
// BindErrors describes all errors when binding params.
type BindErrors []BindError
func (e BindErrors) Error() string {
errStr := make([]string, 0, len(e))
for _, err := range e {
errStr = append(errStr, err.Error())
}
return strings.Join(errStr, ", ")
}
func (e BindErrors) Unwrap() []error {
if len(e) == 0 {
return nil
}
ret := make([]error, 0, len(e))
for _, err := range e {
err := err
ret = append(ret, err)
}
return ret
}
func newBindParam(key string, src BindSource, v any) (BindParam, error) {
vt, fn := getBindFunc(v)
if fn == nil {
return BindParam{}, fmt.Errorf("not support to bind %s key %q to %T", src, key, v)
}
if !src.Valid() {
return BindParam{}, fmt.Errorf("not support bind type %d", src)
}
return BindParam{
Key: key,
From: src,
Type: vt,
Func: fn,
}, nil
}