-
Notifications
You must be signed in to change notification settings - Fork 1
/
json.go
51 lines (37 loc) · 1.1 KB
/
json.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
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package binding
import (
"bytes"
j "encoding/json"
"github.com/ntt360/gin/internal/valid/json"
"github.com/tidwall/gjson"
"io"
"net/http"
)
type jsonBinding struct{}
func (j jsonBinding) Name() string {
return "json"
}
func (j jsonBinding) Bind(req *http.Request, obj any) error {
if req == nil || req.Body == nil {
defGlobalErr.Msg = "invalid request"
return defGlobalErr
}
bodyData, _ := io.ReadAll(req.Body)
// rewrite data
req.Body = io.NopCloser(bytes.NewBuffer(bodyData))
return decodeJSON(bodyData, obj, j.Name())
}
func (j jsonBinding) BindBody(body []byte, obj any) error {
return decodeJSON(body, obj, j.Name())
}
func decodeJSON(content []byte, obj any, validTypeName string) error {
if len(content) > 0 && !j.Valid(content) {
defGlobalErr.Msg = "request data is not valid json"
return defGlobalErr
}
// both valid and bind data to obj
return json.Validate(gjson.ParseBytes(content), obj, validTypeName)
}