json.go
This file
Path
binding/json.go
56 lines · 1.5 KiB · Go
Last changed by
feat: support custom json codec at runtime (#3391)Timbefore adoption688a429
History of this fileTake it
1// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2// Use of this source code is governed by a MIT style3// license that can be found in the LICENSE file.45package binding67import (8 "bytes"9 "errors"10 "io"11 "net/http"1213 "github.com/gin-gonic/gin/codec/json"14)1516// EnableDecoderUseNumber is used to call the UseNumber method on the JSON17// Decoder instance. UseNumber causes the Decoder to unmarshal a number into an18// any as a Number instead of as a float64.19var EnableDecoderUseNumber = false2021// EnableDecoderDisallowUnknownFields is used to call the DisallowUnknownFields method22// on the JSON Decoder instance. DisallowUnknownFields causes the Decoder to23// return an error when the destination is a struct and the input contains object24// keys which do not match any non-ignored, exported fields in the destination.25var EnableDecoderDisallowUnknownFields = false2627type jsonBinding struct{}2829func (jsonBinding) Name() string {30 return "json"31}3233func (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}3940func (jsonBinding) BindBody(body []byte, obj any) error {41 return decodeJSON(bytes.NewReader(body), obj)42}4344func decodeJSON(r io.Reader, obj any) error {45 decoder := json.API.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 err54 }55 return validate(obj)56}