github.com/songzhibin97/gkit@v1.2.13/tools/bind/json.go (about)

     1  package bind
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"io"
     7  	"net/http"
     8  
     9  	"github.com/songzhibin97/gkit/tools/bind/internal/json"
    10  )
    11  
    12  // EnableDecoderUseNumber is used to call the UseNumber method on the JSON
    13  // Decoder instance. UseNumber causes the Decoder to unmarshal a number into an
    14  // interface{} as a Number instead of as a float64.
    15  var EnableDecoderUseNumber = false
    16  
    17  // EnableDecoderDisallowUnknownFields is used to call the DisallowUnknownFields method
    18  // on the JSON Decoder instance. DisallowUnknownFields causes the Decoder to
    19  // return an error when the destination is a struct and the input contains object
    20  // keys which do not match any non-ignored, exported fields in the destination.
    21  var EnableDecoderDisallowUnknownFields = false
    22  
    23  type jsonBinding struct{}
    24  
    25  func (jsonBinding) Name() string {
    26  	return "json"
    27  }
    28  
    29  func (jsonBinding) Bind(req *http.Request, obj interface{}) error {
    30  	if req == nil || req.Body == nil {
    31  		return fmt.Errorf("invalid request")
    32  	}
    33  	return decodeJSON(req.Body, obj)
    34  }
    35  
    36  func (jsonBinding) BindBody(body []byte, obj interface{}) error {
    37  	return decodeJSON(bytes.NewReader(body), obj)
    38  }
    39  
    40  func decodeJSON(r io.Reader, obj interface{}) error {
    41  	decoder := json.NewDecoder(r)
    42  	if EnableDecoderUseNumber {
    43  		decoder.UseNumber()
    44  	}
    45  	if EnableDecoderDisallowUnknownFields {
    46  		decoder.DisallowUnknownFields()
    47  	}
    48  	return decoder.Decode(obj)
    49  }