Merge b03993df0272aa1158ed96f5022fdbb57a188235 into 0f09c3a9b4626d9fe9979cf4d0521d6ae32ab646

This commit is contained in:
water 2026-10-13 02:06:11 -07:00 committed by GitHub
commit f264fbb543
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 273 additions and 6 deletions

View File

@ -9,6 +9,12 @@ import (
"errors"
"io"
"net/http"
"reflect"
"strconv"
"strings"
"time"
stdjson "encoding/json"
"github.com/gin-gonic/gin/codec/json"
)
@ -42,15 +48,213 @@ func (jsonBinding) BindBody(body []byte, obj any) error {
}
func decodeJSON(r io.Reader, obj any) error {
decoder := json.API.NewDecoder(r)
if EnableDecoderUseNumber {
decoder.UseNumber()
body, err := io.ReadAll(r)
if err != nil {
return err
}
if EnableDecoderDisallowUnknownFields {
decoder.DisallowUnknownFields()
// Fast path: standard decode when the struct has no time_format tags.
if !hasTimeFormatTags(obj) {
decoder := json.API.NewDecoder(bytes.NewReader(body))
if EnableDecoderUseNumber {
decoder.UseNumber()
}
if EnableDecoderDisallowUnknownFields {
decoder.DisallowUnknownFields()
}
if err := decoder.Decode(obj); err != nil {
return err
}
return validate(obj)
}
if err := decoder.Decode(obj); err != nil {
// Slow path: decode field-by-field so that time.Time fields with a
// time_format tag are parsed by setTimeField instead of the standard
// JSON decoder (which only understands RFC3339).
if err := decodeJSONWithTimeFormat(body, obj); err != nil {
return err
}
return validate(obj)
}
// ---------------------------------------------------------------------------
// time_format tag support
// ---------------------------------------------------------------------------
// jsonKey returns the JSON object key for a struct field, respecting the
// "json" struct tag. It returns the field name when no tag is present.
func jsonKey(field reflect.StructField) string {
tag, ok := field.Tag.Lookup("json")
if !ok {
return field.Name
}
if idx := strings.IndexByte(tag, ','); idx >= 0 {
tag = tag[:idx]
}
if tag == "" || tag == "-" {
return field.Name
}
return tag
}
// hasTimeFormatTags returns true when the value (or any nested struct reachable
// through exported fields) contains at least one time.Time field with a
// non-empty time_format struct tag.
func hasTimeFormatTags(obj any) bool {
rv := reflect.ValueOf(obj)
if rv.Kind() == reflect.Ptr {
rv = rv.Elem()
}
return hasTimeFormatTagsValue(rv)
}
func hasTimeFormatTagsValue(rv reflect.Value) bool {
if rv.Kind() != reflect.Struct {
return false
}
t := rv.Type()
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if !field.IsExported() {
continue
}
if field.Tag.Get("time_format") != "" {
return true
}
ft := field.Type
if ft == reflect.TypeOf(time.Time{}) {
continue
}
// Recurse into nested structs and pointer-to-structs.
switch ft.Kind() {
case reflect.Struct:
if hasTimeFormatTagsValue(reflect.New(ft).Elem()) {
return true
}
case reflect.Ptr:
if ft.Elem().Kind() == reflect.Struct &&
hasTimeFormatTagsValue(reflect.New(ft.Elem()).Elem()) {
return true
}
}
}
return false
}
// decodeJSONWithTimeFormat decodes a JSON body into a struct, handling
// time.Time fields that carry a time_format tag by parsing them with
// setTimeField instead of the standard JSON decoder.
func decodeJSONWithTimeFormat(body []byte, obj any) error {
rv := reflect.ValueOf(obj)
if rv.Kind() == reflect.Ptr {
rv = rv.Elem()
}
return decodeJSONValue(body, rv)
}
func decodeJSONValue(body []byte, rv reflect.Value) error {
switch rv.Kind() {
case reflect.Struct:
// Unmarshal the raw body into a map of raw JSON messages so we can
// process each field individually.
var rawMap map[string]stdjson.RawMessage
if err := stdjson.Unmarshal(body, &rawMap); err != nil {
return err
}
t := rv.Type()
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if !field.IsExported() {
continue
}
key := jsonKey(field)
raw, ok := rawMap[key]
if !ok {
continue
}
fv := rv.Field(i)
if err := decodeField(raw, field, fv); err != nil {
return err
}
}
return nil
case reflect.Slice, reflect.Array:
var items []stdjson.RawMessage
if err := stdjson.Unmarshal(body, &items); err != nil {
return err
}
for i := 0; i < rv.Len() && i < len(items); i++ {
if err := decodeJSONValue(items[i], rv.Index(i)); err != nil {
return err
}
}
return nil
default:
return json.API.Unmarshal(body, rv.Addr().Interface())
}
}
func decodeField(raw stdjson.RawMessage, field reflect.StructField, fv reflect.Value) error {
ft := field.Type
// time.Time with time_format tag → use setTimeField.
if ft == reflect.TypeOf(time.Time{}) && field.Tag.Get("time_format") != "" {
rawStr, err := rawToStr(raw)
if err != nil {
return nil // skip unparseable values
}
return setTimeField(rawStr, field, fv)
}
// *time.Time with time_format tag → allocate, parse, set pointer.
if ft.Kind() == reflect.Ptr && ft.Elem() == reflect.TypeOf(time.Time{}) &&
field.Tag.Get("time_format") != "" {
rawStr, err := rawToStr(raw)
if err != nil {
return nil
}
newTime := reflect.New(reflect.TypeOf(time.Time{})).Elem()
if err := setTimeField(rawStr, field, newTime); err != nil {
return err
}
fv.Set(newTime.Addr())
return nil
}
// Nested struct → recurse.
if ft.Kind() == reflect.Struct && ft != reflect.TypeOf(time.Time{}) {
return decodeJSONValue(raw, fv)
}
// Pointer to nested struct → allocate if nil, then recurse.
if ft.Kind() == reflect.Ptr && ft.Elem().Kind() == reflect.Struct && ft.Elem() != reflect.TypeOf(time.Time{}) {
if fv.IsNil() {
fv.Set(reflect.New(ft.Elem()))
}
return decodeJSONValue(raw, fv.Elem())
}
// All other types: standard JSON unmarshal.
return json.API.Unmarshal(raw, fv.Addr().Interface())
}
// rawToStr extracts a string value from a raw JSON message, handling both
// quoted strings and numeric values (unix timestamps).
func rawToStr(raw stdjson.RawMessage) (string, error) {
var s string
if err := stdjson.Unmarshal(raw, &s); err == nil {
return s, nil
}
var n int64
if err := stdjson.Unmarshal(raw, &n); err == nil {
return strconv.FormatInt(n, 10), nil
}
var f float64
if err := stdjson.Unmarshal(raw, &f); err == nil {
return strconv.FormatFloat(f, 'f', -1, 64), nil
}
return "", errors.New("not a string or number")
}

View File

@ -0,0 +1,63 @@
// Copyright 2019 Gin Core Team. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package binding
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type timeFormatReq struct {
Timestamp time.Time `json:"Timestamp" time_format:"2006-01-02 15:04:05"`
UnixTime time.Time `json:"UnixTime" time_format:"unix"`
Plain time.Time `json:"Plain"`
}
func TestJSONBindingTimeFormat(t *testing.T) {
var s timeFormatReq
err := jsonBinding{}.BindBody([]byte(`{
"Timestamp": "2001-11-11 11:11:11",
"UnixTime": 1575528300,
"Plain": "2001-11-11T11:11:11Z"
}`), &s)
require.NoError(t, err)
// Custom time_format tag is honored.
assert.Equal(t, time.Date(2001, 11, 11, 11, 11, 11, 0, time.Local), s.Timestamp)
// unix time_format tag is honored.
assert.Equal(t, time.Unix(1575528300, 0), s.UnixTime)
// Fields without a time_format tag keep default RFC3339 parsing.
assert.Equal(t, time.Date(2001, 11, 11, 11, 11, 11, 0, time.UTC), s.Plain)
}
type timeFormatPtrReq struct {
Timestamp *time.Time `json:"Timestamp" time_format:"2006-01-02 15:04:05"`
}
func TestJSONBindingTimeFormatPointer(t *testing.T) {
var s timeFormatPtrReq
err := jsonBinding{}.BindBody([]byte(`{"Timestamp": "2020-01-02 03:04:05"}`), &s)
require.NoError(t, err)
require.NotNil(t, s.Timestamp)
assert.Equal(t, time.Date(2020, 1, 2, 3, 4, 5, 0, time.Local), *s.Timestamp)
}
type timeFormatNested struct {
Inner struct {
When time.Time `json:"when" time_format:"2006-01-02"`
} `json:"inner"`
}
func TestJSONBindingTimeFormatNested(t *testing.T) {
var s timeFormatNested
err := jsonBinding{}.BindBody([]byte(`{"inner": {"when": "2019-12-07"}}`), &s)
require.NoError(t, err)
assert.Equal(t, time.Date(2019, 12, 7, 0, 0, 0, 0, time.Local), s.Inner.When)
}