2022-05-28 05:42:28 +03:00
|
|
|
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
2015-03-31 18:51:10 +03:00
|
|
|
// Use of this source code is governed by a MIT style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package binding
|
|
|
|
|
|
|
|
import (
|
2018-05-11 05:33:33 +03:00
|
|
|
"bytes"
|
2021-04-28 13:39:09 +03:00
|
|
|
"errors"
|
2018-05-11 05:33:33 +03:00
|
|
|
"io"
|
2015-03-31 18:51:10 +03:00
|
|
|
"net/http"
|
2017-07-08 11:49:09 +03:00
|
|
|
|
2022-12-12 14:48:00 +03:00
|
|
|
"git.internal/re/gin/internal/json"
|
2015-03-31 18:51:10 +03:00
|
|
|
)
|
|
|
|
|
2018-03-29 09:33:07 +03:00
|
|
|
// EnableDecoderUseNumber is used to call the UseNumber method on the JSON
|
|
|
|
// Decoder instance. UseNumber causes the Decoder to unmarshal a number into an
|
|
|
|
// interface{} as a Number instead of as a float64.
|
2017-10-29 15:12:22 +03:00
|
|
|
var EnableDecoderUseNumber = false
|
2017-07-08 13:19:09 +03:00
|
|
|
|
2019-09-06 08:56:59 +03:00
|
|
|
// EnableDecoderDisallowUnknownFields is used to call the DisallowUnknownFields method
|
|
|
|
// on the JSON Decoder instance. DisallowUnknownFields causes the Decoder to
|
|
|
|
// return an error when the destination is a struct and the input contains object
|
|
|
|
// keys which do not match any non-ignored, exported fields in the destination.
|
|
|
|
var EnableDecoderDisallowUnknownFields = false
|
|
|
|
|
2015-03-31 18:51:10 +03:00
|
|
|
type jsonBinding struct{}
|
|
|
|
|
2015-07-10 14:06:01 +03:00
|
|
|
func (jsonBinding) Name() string {
|
2015-03-31 18:51:10 +03:00
|
|
|
return "json"
|
|
|
|
}
|
|
|
|
|
2022-03-21 04:43:17 +03:00
|
|
|
func (jsonBinding) Bind(req *http.Request, obj any) error {
|
2018-11-22 04:55:51 +03:00
|
|
|
if req == nil || req.Body == nil {
|
2021-04-28 13:39:09 +03:00
|
|
|
return errors.New("invalid request")
|
2018-11-22 04:55:51 +03:00
|
|
|
}
|
2018-05-11 05:33:33 +03:00
|
|
|
return decodeJSON(req.Body, obj)
|
|
|
|
}
|
|
|
|
|
2022-03-21 04:43:17 +03:00
|
|
|
func (jsonBinding) BindBody(body []byte, obj any) error {
|
2018-05-11 05:33:33 +03:00
|
|
|
return decodeJSON(bytes.NewReader(body), obj)
|
|
|
|
}
|
|
|
|
|
2022-03-21 04:43:17 +03:00
|
|
|
func decodeJSON(r io.Reader, obj any) error {
|
2018-05-11 05:33:33 +03:00
|
|
|
decoder := json.NewDecoder(r)
|
2017-07-10 11:33:35 +03:00
|
|
|
if EnableDecoderUseNumber {
|
|
|
|
decoder.UseNumber()
|
|
|
|
}
|
2019-09-06 08:56:59 +03:00
|
|
|
if EnableDecoderDisallowUnknownFields {
|
|
|
|
decoder.DisallowUnknownFields()
|
|
|
|
}
|
2015-04-07 13:30:16 +03:00
|
|
|
if err := decoder.Decode(obj); err != nil {
|
2015-03-31 18:51:10 +03:00
|
|
|
return err
|
|
|
|
}
|
2015-05-31 17:30:00 +03:00
|
|
|
return validate(obj)
|
2015-03-31 18:51:10 +03:00
|
|
|
}
|