...
  
  
     1  
     2  
     3  
     4  
     5  package binding
     6  
     7  import (
     8  	"bytes"
     9  	"errors"
    10  	"io"
    11  	"net/http"
    12  
    13  	"github.com/gin-gonic/gin/internal/json"
    14  )
    15  
    16  
    17  
    18  
    19  var EnableDecoderUseNumber = false
    20  
    21  
    22  
    23  
    24  
    25  var EnableDecoderDisallowUnknownFields = false
    26  
    27  type jsonBinding struct{}
    28  
    29  func (jsonBinding) Name() string {
    30  	return "json"
    31  }
    32  
    33  func (jsonBinding) Bind(req *http.Request, obj any) error {
    34  	if req == nil || req.Body == nil {
    35  		return errors.New("invalid request")
    36  	}
    37  	return decodeJSON(req.Body, obj)
    38  }
    39  
    40  func (jsonBinding) BindBody(body []byte, obj any) error {
    41  	return decodeJSON(bytes.NewReader(body), obj)
    42  }
    43  
    44  func decodeJSON(r io.Reader, obj any) error {
    45  	decoder := json.NewDecoder(r)
    46  	if EnableDecoderUseNumber {
    47  		decoder.UseNumber()
    48  	}
    49  	if EnableDecoderDisallowUnknownFields {
    50  		decoder.DisallowUnknownFields()
    51  	}
    52  	if err := decoder.Decode(obj); err != nil {
    53  		return err
    54  	}
    55  	return validate(obj)
    56  }
    57  
View as plain text