【问题标题】:How do I bind a date string to a struct?如何将日期字符串绑定到结构?
【发布时间】:2021-11-19 08:46:16
【问题描述】:
type TestModel struct {
  Date     time.Time `json:"date" form:"date" gorm:"index"`
  gorm.Model
}

我正在使用 echo 框架,并且 我有一个像上面这样的结构,我得到像 '2021-09-27' 这样的字符串数据,如何将它绑定到结构?

func CreateDiary(c echo.Context) error {
    var getData model.TestModel
    if err := (&echo.DefaultBinder{}).BindBody(c, &getData); err != nil {
        fmt.Print(err.Error())
    }
   return c.JSON(200, getData)
}

当我这样编码时,我收到以下错误:

code=400, message=parsing time "2021-09-27" as "2006-01-02T15:04:05Z07:00": cannot parse "" as "T", internal=parsing time "2021-09-27" as "2006-01-02T15:04:05Z07:00": cannot parse "" as "T"

我是一个golang初学者,你能给我一个简单的例子吗??拜托。

我正在使用回显框架

【问题讨论】:

标签: go time echo bind glide-golang


【解决方案1】:

这里是 echo 中使用的可用标签列表。如果要从正文中解析,请使用 json

  • 查询 - 来源是请求查询参数。
  • param - source 是路由路径参数。
  • 标头 - 来源是标头参数。
  • 表格 - 来源是表格。值取自查询和请求正文。使用 Go 标准库表单解析。
  • json - 源是请求正文。使用 Go json 包进行解组。
  • xml - 源是请求正文。使用 Go xml 包进行解组。

您需要将 time.Time 包装到自定义结构中,然后实现 json.Marshalerjson.Unmarshaler 接口

示例

package main

import (
    "fmt"
    "strings"
    "time"

    "github.com/labstack/echo/v4"
)

type CustomTime struct {
    time.Time
}

type TestModel struct {
    Date CustomTime `json:"date"`
}

func (t CustomTime) MarshalJSON() ([]byte, error) {
    date := t.Time.Format("2006-01-02")
    date = fmt.Sprintf(`"%s"`, date)
    return []byte(date), nil
}

func (t *CustomTime) UnmarshalJSON(b []byte) (err error) {
    s := strings.Trim(string(b), "\"")

    date, err := time.Parse("2006-01-02", s)
    if err != nil {
        return err
    }
    t.Time = date
    return
}

func main() {
    e := echo.New()
    e.POST("/test", CreateDiary)
    e.Logger.Fatal(e.Start(":1323"))
}

func CreateDiary(c echo.Context) error {
    var getData TestModel
    if err := (&echo.DefaultBinder{}).BindBody(c, &getData); err != nil {
        fmt.Print(err.Error())
    }
    return c.JSON(200, getData)
}

测试

curl -X POST http://localhost:1323/test -H 'Content-Type: application/json' -d '{"date":"2021-09-27"}'

【讨论】:

  • 如何将 MarshalJSON 与 c.bind() 一起使用?
  • 你不需要。回声框架会照顾。查看更新的答案。
  • 当我执行 c.bind 时,MarshalJSON 似乎可以工作,但结果是“0001-01-01”我从 接收数据
  • 您能显示您发送的具体数据吗?理想情况下通过 curl
【解决方案2】:

键入CustomTime time.Time

func (ct *CustomTime) UnmarshalParam(param string) error {
    t, err := time.Parse(`2006-01-02`, param)
    if err != nil {
        return err
    }
    *ct = CustomTime(t)
    return nil
}

参考:https://github.com/labstack/echo/issues/1571

【讨论】:

  • 如何将 UnmarshalParam 与 c.bind() 一起使用?
  • 这行不通,因为@Choiyunseok 试图解组身体而不是参数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-30
  • 1970-01-01
  • 1970-01-01
  • 2020-01-30
  • 2011-02-12
  • 1970-01-01
相关资源
最近更新 更多