gtsocial-umbx

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

json.go (1542B)


      1 // Copyright 2014 Manu Martinez-Almeida. All rights reserved.
      2 // Use of this source code is governed by a MIT style
      3 // license that can be found in the LICENSE file.
      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 // EnableDecoderUseNumber is used to call the UseNumber method on the JSON
     17 // Decoder instance. UseNumber causes the Decoder to unmarshal a number into an
     18 // any as a Number instead of as a float64.
     19 var EnableDecoderUseNumber = false
     20 
     21 // EnableDecoderDisallowUnknownFields is used to call the DisallowUnknownFields method
     22 // on the JSON Decoder instance. DisallowUnknownFields causes the Decoder to
     23 // return an error when the destination is a struct and the input contains object
     24 // keys which do not match any non-ignored, exported fields in the destination.
     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 }