-
Notifications
You must be signed in to change notification settings - Fork 4
/
binder.go
54 lines (42 loc) · 1001 Bytes
/
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
package gini
import (
"encoding/json"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
)
// Binder to parse request body to struct.
type Binder interface {
Bind(*gin.Context, interface{}) error
}
var (
binder Binder
)
func init() {
binder = &defaultBinder{}
}
type defaultBinder struct {
}
func (db *defaultBinder) Bind(ctx *gin.Context, v interface{}) error {
b := binding.Default(ctx.Request.Method, ctx.ContentType())
return ctx.MustBindWith(v, b)
}
// SetBinder set Binder instance.
func SetBinder(b Binder) {
binder = b
}
// Bind to parse request body to struct.
func Bind(ctx *gin.Context, v interface{}) error {
return binder.Bind(ctx, v)
}
// MockJSONBinder json binder for mock.
type MockJSONBinder struct {
body string
}
// Body set request body
func (mb *MockJSONBinder) Body(body string) {
mb.body = body
}
// Bind for Binder interface.
func (mb *MockJSONBinder) Bind(c *gin.Context, v interface{}) error {
return json.Unmarshal([]byte(mb.body), v)
}