Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: binding time with empty value #4098 #4103

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions binding/form_mapping.go
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,10 @@ func setTimeField(val string, structField reflect.StructField, value reflect.Val

switch tf := strings.ToLower(timeFormat); tf {
case "unix", "unixnano":
if val == "" {
val = "0"
}

tv, err := strconv.ParseInt(val, 10, 64)
if err != nil {
return err
Expand Down
23 changes: 13 additions & 10 deletions binding/form_mapping_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,30 +183,33 @@ func TestMapFormWithTag(t *testing.T) {

func TestMappingTime(t *testing.T) {
var s struct {
Time time.Time
LocalTime time.Time `time_format:"2006-01-02"`
ZeroValue time.Time
CSTTime time.Time `time_format:"2006-01-02" time_location:"Asia/Shanghai"`
UTCTime time.Time `time_format:"2006-01-02" time_utc:"1"`
Time time.Time
LocalTime time.Time `time_format:"2006-01-02"`
ZeroValue time.Time
ZeroUnixTime time.Time `time_format:"unix"` // see issue #4098
CSTTime time.Time `time_format:"2006-01-02" time_location:"Asia/Shanghai"`
UTCTime time.Time `time_format:"2006-01-02" time_utc:"1"`
}

var err error
time.Local, err = time.LoadLocation("Europe/Berlin")
require.NoError(t, err)

err = mapForm(&s, map[string][]string{
"Time": {"2019-01-20T16:02:58Z"},
"LocalTime": {"2019-01-20"},
"ZeroValue": {},
"CSTTime": {"2019-01-20"},
"UTCTime": {"2019-01-20"},
"Time": {"2019-01-20T16:02:58Z"},
"LocalTime": {"2019-01-20"},
"ZeroValue": {},
"ZeroUnixTime": {},
"CSTTime": {"2019-01-20"},
"UTCTime": {"2019-01-20"},
})
require.NoError(t, err)

assert.Equal(t, "2019-01-20 16:02:58 +0000 UTC", s.Time.String())
assert.Equal(t, "2019-01-20 00:00:00 +0100 CET", s.LocalTime.String())
assert.Equal(t, "2019-01-19 23:00:00 +0000 UTC", s.LocalTime.UTC().String())
assert.Equal(t, "0001-01-01 00:00:00 +0000 UTC", s.ZeroValue.String())
assert.Equal(t, "1970-01-01 00:00:00 +0000 UTC", s.ZeroUnixTime.UTC().String())
assert.Equal(t, "2019-01-20 00:00:00 +0800 CST", s.CSTTime.String())
assert.Equal(t, "2019-01-19 16:00:00 +0000 UTC", s.CSTTime.UTC().String())
assert.Equal(t, "2019-01-20 00:00:00 +0000 UTC", s.UTCTime.String())
Expand Down