Skip to content

Commit

Permalink
Support time location on form binding (#1117)
Browse files Browse the repository at this point in the history
  • Loading branch information
delphinus authored and appleboy committed Sep 28, 2017
1 parent 5afc5b1 commit a8c5394
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
8 changes: 8 additions & 0 deletions binding/form_mapping.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 13 additions & 8 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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")
Expand All @@ -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")
Expand Down

0 comments on commit a8c5394

Please sign in to comment.