Golang 大猩猩从表单中解析具有特定格式的日期
Golang gorilla parse date with specific format from form
我从表格中收到日期。此日期具有特定格式 "dd/mm/yyyy"。
为了将它解析为我的结构,我使用了 gorilla/schema 包,但是这个包无法将接收到的数据识别为日期。
我如何解析日期并将其以正确的方式放入结构中?作为字段,它的格式为“01/02/2006”
我的实现:
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)
}
.......................
}
我没有测试这个答案,因为我没有时间建立一个例子,但是根据这个: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.
所以你需要说:
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)
}
}
我从表格中收到日期。此日期具有特定格式 "dd/mm/yyyy"。
为了将它解析为我的结构,我使用了 gorilla/schema 包,但是这个包无法将接收到的数据识别为日期。
我如何解析日期并将其以正确的方式放入结构中?作为字段,它的格式为“01/02/2006”
我的实现:
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)
}
.......................
}
我没有测试这个答案,因为我没有时间建立一个例子,但是根据这个: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.
所以你需要说:
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)
}
}