From a8c53949e5b7d8a00a9e26b1609a7626e7d0b127 Mon Sep 17 00:00:00 2001 From: delphinus Date: Thu, 28 Sep 2017 23:23:18 +0900 Subject: [PATCH] Support time location on form binding (#1117) --- binding/form_mapping.go | 8 ++++++++ context_test.go | 21 +++++++++++++-------- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/binding/form_mapping.go b/binding/form_mapping.go index 34f12678..c968dc08 100644 --- a/binding/form_mapping.go +++ b/binding/form_mapping.go @@ -163,6 +163,14 @@ func setTimeField(val string, structField reflect.StructField, value reflect.Val l = time.UTC } + if locTag := structField.Tag.Get("time_location"); locTag != "" { + loc, err := time.LoadLocation(locTag) + if err != nil { + return err + } + l = loc + } + t, err := time.ParseInLocation(timeFormat, val, l) if err != nil { return err diff --git a/context_test.go b/context_test.go index 15569bf2..4854a8a8 100644 --- a/context_test.go +++ b/context_test.go @@ -45,6 +45,7 @@ func createMultipartRequest() *http.Request { must(mw.WriteField("id", "")) must(mw.WriteField("time_local", "31/12/2016 14:55")) must(mw.WriteField("time_utc", "31/12/2016 14:55")) + must(mw.WriteField("time_location", "31/12/2016 14:55")) req, err := http.NewRequest("POST", "/", body) must(err) req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary) @@ -444,14 +445,15 @@ func TestContextPostFormMultipart(t *testing.T) { c.Request = createMultipartRequest() var obj struct { - Foo string `form:"foo"` - Bar string `form:"bar"` - BarAsInt int `form:"bar"` - Array []string `form:"array"` - ID string `form:"id"` - TimeLocal time.Time `form:"time_local" time_format:"02/01/2006 15:04"` - TimeUTC time.Time `form:"time_utc" time_format:"02/01/2006 15:04" time_utc:"1"` - BlankTime time.Time `form:"blank_time" time_format:"02/01/2006 15:04"` + Foo string `form:"foo"` + Bar string `form:"bar"` + BarAsInt int `form:"bar"` + Array []string `form:"array"` + ID string `form:"id"` + TimeLocal time.Time `form:"time_local" time_format:"02/01/2006 15:04"` + TimeUTC time.Time `form:"time_utc" time_format:"02/01/2006 15:04" time_utc:"1"` + TimeLocation time.Time `form:"time_location" time_format:"02/01/2006 15:04" time_location:"Asia/Tokyo"` + BlankTime time.Time `form:"blank_time" time_format:"02/01/2006 15:04"` } assert.NoError(t, c.Bind(&obj)) assert.Equal(t, obj.Foo, "bar") @@ -463,6 +465,9 @@ func TestContextPostFormMultipart(t *testing.T) { assert.Equal(t, obj.TimeLocal.Location(), time.Local) assert.Equal(t, obj.TimeUTC.Format("02/01/2006 15:04"), "31/12/2016 14:55") assert.Equal(t, obj.TimeUTC.Location(), time.UTC) + loc, _ := time.LoadLocation("Asia/Tokyo") + assert.Equal(t, obj.TimeLocation.Format("02/01/2006 15:04"), "31/12/2016 14:55") + assert.Equal(t, obj.TimeLocation.Location(), loc) assert.True(t, obj.BlankTime.IsZero()) value, ok := c.GetQuery("foo")