dongxiequ3724 2018-03-14 18:51
浏览 34
已采纳

Golang大猩猩从表格中解析特定格式的日期

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)
  }
  .......................
}
  • 写回答

2条回答 默认 最新

  • donglan8870 2018-03-15 18:19
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?