From b03993df0272aa1158ed96f5022fdbb57a188235 Mon Sep 17 00:00:00 2001 From: waterWang Date: Mon, 10 Aug 2026 09:51:07 +0800 Subject: [PATCH] fix(binding): respect time_format tag in JSON binding (ShouldBindJSON) The time_format, time_utc, and time_location struct tags work correctly for form/query binding (ShouldBindQuery, ShouldBindForm) but are completely ignored when using ShouldBindJSON or ShouldBindBodyWithJSON. encoding/json only understands RFC3339 for time.Time fields, so custom time formats such as "2006-01-02 15:04:05" or "unix" produce a parse error like: parsing time "2001-11-11 11:11:11" as "2006-01-02T15:04:05Z07:00": cannot parse " 11:11:11" as "T" This fix replaces the single-pass JSON decode with a field-by-field decode when the target struct has any time.Time field that carries a time_format tag. Fields with time_format are parsed by the existing setTimeField helper (same one used by form binding), so all existing tag features (time_format, time_utc, time_location, unix/unixmilli/ unixmicro/unixnano) work identically in JSON binding. Fast path: when the struct has no time_format tags at all, the original single-pass decoder.Decode path is used (zero overhead). Fixes #2170 --- binding/json.go | 216 ++++++++++++++++++++++++++++++- binding/json_time_format_test.go | 63 +++++++++ 2 files changed, 273 insertions(+), 6 deletions(-) create mode 100644 binding/json_time_format_test.go diff --git a/binding/json.go b/binding/json.go index f4ae921a..51820b54 100644 --- a/binding/json.go +++ b/binding/json.go @@ -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") +} \ No newline at end of file diff --git a/binding/json_time_format_test.go b/binding/json_time_format_test.go new file mode 100644 index 00000000..dc3d755f --- /dev/null +++ b/binding/json_time_format_test.go @@ -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) +} \ No newline at end of file