-
Notifications
You must be signed in to change notification settings - Fork 16
/
binder.go
82 lines (70 loc) · 1.47 KB
/
binder.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
package binding
import (
"net/http"
)
type (
// Binder interface
Binder interface {
Name() string
Bind(r *http.Request, obj any) error
}
// BinderFunc bind func, implement the Binder() interface
BinderFunc func(r *http.Request, obj any) error
// DataValidator interface
DataValidator interface {
Validate(i any) error
}
)
// build-in data binder
var (
Form = FormBinder{FormTagName}
Header = HeaderBinder{HeaderTagName}
Query = QueryBinder{QueryTagName}
JSON = JSONBinder{}
XML = XMLBinder{}
// TODO more driver
// YAML = YAMLBinder{}
// MSGPACK = MSGPACKBinder{}
// PROTOBUF = PROTOBUFBinder{}
// Binders mapping
Binders = map[string]Binder{
"xml": XML,
"json": JSON,
"query": Query,
"form": Form,
"header": Header,
// TODO more driver
// "yaml": YAML,
// "msgpack": MSGPACK,
// "protobuf": PROTOBUF,
}
)
// Name implements the Binder interface
func (fn BinderFunc) Name() string {
return "unknown"
}
// Bind implements the Binder interface
func (fn BinderFunc) Bind(r *http.Request, obj any) error {
return fn(r, obj)
}
// GetBinder get an binder by name
func GetBinder(name string) Binder {
if b, ok := Binders[name]; ok {
return b
}
return nil
}
// Register new binder with name
func Register(name string, b Binder) {
if name != "" && b != nil {
Binders[name] = b
}
}
// Remove exists binder(s)
func Remove(names ...string) {
for _, name := range names {
if _, ok := Binders[name]; ok {
delete(Binders, name)
}
}
}