Reputation: 3722
I receive date from form. This date has specific format "dd/mm/yyyy".
For parsing it to my struct I use gorilla/schema package, but this package can't recognize received data as date.
How I can parse date and put it in struct right way? As field it has format "01/02/2006"
My implementation:
type User struct {
Date time.Time `schema:"date"`
}
func MyRoute(w http.ResponseWriter, r *http.Request) {
user := User{}
r.ParseForm()
defer r.Body.Close()
decoder := schema.NewDecoder()
if err := decoder.Decode(&user, r.Form); err != nil {
fmt.Println(err)
}
.......................
}
Upvotes: 1
Views: 3034
Reputation: 977
I haven't tested this answer because I don't have time to build up an example, but according to this: http://www.gorillatoolkit.org/pkg/schema
The supported field types in the destination struct are:
- bool
- float variants (float32, float64)
- int variants (int, int8, int16, int32, int64)
- string
- uint variants (uint, uint8, uint16, uint32, uint64)
- struct
- a pointer to one of the above types
- a slice or a pointer to a slice of one of the above types
Non-supported types are simply ignored, however custom types can be registered to be converted.
so you need to say:
var timeConverter = func(value string) reflect.Value {
if v, err := time.Parse("02/01/2006", value); err == nil {
return reflect.ValueOf(v)
}
return reflect.Value{} // this is the same as the private const invalidType
}
func MyRoute(w http.ResponseWriter, r *http.Request) {
user := User{}
r.ParseForm()
defer r.Body.Close()
decoder := schema.NewDecoder()
decoder.RegisterConverter(time.Time{}, timeConverter)
if err := decoder.Decode(&user, r.Form); err != nil {
fmt.Println(err)
}
}
see: https://github.com/gorilla/schema/blob/master/decoder.go
Upvotes: 4