/
context_external.go
114 lines (95 loc) · 2.5 KB
/
context_external.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
113
114
package gin
import (
"github.com/nilpanic/gin/internal/rsp"
"github.com/nilpanic/gin/internal/valid/binding"
r "github.com/nilpanic/gin/rsp"
"io"
"net/http"
)
func (c *Context) Valid(obj any) error {
b := binding.Default(c.Request.Method, c.ContentType())
return c.ShouldBindWith(obj, b)
}
// ValidJSON is a shortcut for c.ValidWith(obj, binding.JSON).
func (c *Context) ValidJSON(obj any) error {
return c.ShouldBindWith(obj, binding.JSON)
}
// ValidQuery is a shortcut for c.ValidWith(obj, binding.Query).
func (c *Context) ValidQuery(obj any) error {
return c.ShouldBindWith(obj, binding.Query)
}
// ValidHeader is a shortcut for c.ShouldBindWith(obj, binding.Header).
func (c *Context) ValidHeader(obj any) error {
return c.ShouldBindWith(obj, binding.Header)
}
// ValidWith binds the passed struct pointer using the specified binding engine.
// See the binding package.
func (c *Context) ValidWith(obj any, b binding.Binding) error {
return b.Bind(c.Request, obj)
}
// ValidBodyWith is similar with ValidWith, but it stores the request
// body into the context, and reuse when it is called again.
//
// NOTE: This method reads the body before binding. So you should use
// ValidBodyWith for better performance if you need to call only once.
func (c *Context) ValidBodyWith(obj any, bb binding.BindingBody) (err error) {
var body []byte
if cb, ok := c.Get(BodyBytesKey); ok {
if cbb, ok := cb.([]byte); ok {
body = cbb
}
}
if body == nil {
body, err = io.ReadAll(c.Request.Body)
if err != nil {
return err
}
c.Set(BodyBytesKey, body)
}
return bb.BindBody(body, obj)
}
// JSONOk response json success data.
func (c *Context) JSONOk(val ...rsp.JSVal) {
rel := &rsp.JSONVal{
Code: r.CodeOK,
Msg: r.MsgSuccess,
}
for _, jsonVal := range val {
jsonVal(rel)
}
c.JSON(http.StatusOK, rel)
}
// JSONErr response json error data.
func (c *Context) JSONErr(val ...rsp.JSVal) {
rel := &rsp.JSONVal{
Code: r.CodeErr,
Msg: r.MsgFailed,
}
for _, jsonVal := range val {
jsonVal(rel)
}
c.JSON(http.StatusOK, rel)
}
// JSONPOk response jsonp success data.
func (c *Context) JSONPOk(val ...rsp.JSVal) {
rel := &rsp.JSONVal{
Code: r.CodeOK,
Msg: r.MsgSuccess,
}
for _, jsonVal := range val {
jsonVal(rel)
}
c.JSONP(http.StatusOK, rel)
}
// JSONPErr response jsonp error data.
func (c *Context) JSONPErr(val ...rsp.JSVal) {
rel := &rsp.JSONVal{
Code: r.CodeErr,
Msg: r.MsgFailed,
Data: nil,
}
for _, jsonVal := range val {
jsonVal(rel)
}
c.JSONP(http.StatusOK, rel)
}