mirror of
https://github.com/gin-gonic/gin.git
synced 2025-10-24 02:32:17 +08:00
Auto-detect time format in form binding
This commit is contained in:
parent
7b508186dd
commit
f4755ac9fa
@ -9,6 +9,7 @@ import (
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin/binding/example"
|
||||
"github.com/golang/protobuf/proto"
|
||||
@ -284,3 +285,14 @@ func requestWithBody(method, path, body string) (req *http.Request) {
|
||||
req, _ = http.NewRequest(method, path, bytes.NewBufferString(body))
|
||||
return
|
||||
}
|
||||
|
||||
func TestBindingFormOptionalTimeFormat(t *testing.T) {
|
||||
q := struct {
|
||||
Date time.Time `form:"date"`
|
||||
}{}
|
||||
req, _ := http.NewRequest(http.MethodGet, "/?date=2017-07-20", nil)
|
||||
b := Form
|
||||
err := b.Bind(req, &q)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, time.Date(2017, time.July, 20, 0, 0, 0, 0, time.Local), q.Date)
|
||||
}
|
||||
|
@ -9,6 +9,8 @@ import (
|
||||
"reflect"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/araddon/dateparse"
|
||||
)
|
||||
|
||||
func mapForm(ptr interface{}, form map[string][]string) error {
|
||||
@ -148,22 +150,29 @@ func setFloatField(val string, bitSize int, field reflect.Value) error {
|
||||
}
|
||||
|
||||
func setTimeField(val string, structField reflect.StructField, value reflect.Value) error {
|
||||
timeFormat := structField.Tag.Get("time_format")
|
||||
if timeFormat == "" {
|
||||
return errors.New("Blank time format")
|
||||
}
|
||||
|
||||
if val == "" {
|
||||
value.Set(reflect.ValueOf(time.Time{}))
|
||||
return nil
|
||||
}
|
||||
|
||||
timeFormat := structField.Tag.Get("time_format")
|
||||
|
||||
l := time.Local
|
||||
if isUTC, _ := strconv.ParseBool(structField.Tag.Get("time_utc")); isUTC {
|
||||
l = time.UTC
|
||||
}
|
||||
|
||||
t, err := time.ParseInLocation(timeFormat, val, l)
|
||||
var t time.Time
|
||||
var err error
|
||||
switch timeFormat {
|
||||
case "":
|
||||
t, err = dateparse.ParseIn(val, l)
|
||||
default:
|
||||
t, err = time.ParseInLocation(timeFormat, val, l)
|
||||
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
6
vendor/vendor.json
vendored
6
vendor/vendor.json
vendored
@ -2,6 +2,12 @@
|
||||
"comment": "v1.2",
|
||||
"ignore": "test",
|
||||
"package": [
|
||||
{
|
||||
"checksumSHA1": "5P/i6wl4VszvH+3ep0egh4C/BDM=",
|
||||
"path": "github.com/araddon/dateparse",
|
||||
"revision": "a1537bb04470047339734bb11c0403cbc41c31aa",
|
||||
"revisionTime": "2017-07-27T05:39:44Z"
|
||||
},
|
||||
{
|
||||
"checksumSHA1": "dvabztWVQX8f6oMLRyv4dLH+TGY=",
|
||||
"comment": "v1.1.0",
|
||||
|
Loading…
x
Reference in New Issue
Block a user