Golang Fiber的BodyParser用于解析时间。

huangapple go评论76阅读模式
英文:

golang fiber bodyparser to parse Time

问题

在我的项目中,我正在使用Fiber BodyParser来解析我的端点接收到的JSON数据。我可以解析整数和字符串,但是如果我需要解析时间怎么办?请考虑以下代码:

app.Post("/post", func(c *fiber.Ctx) error {
    payload := struct {
        Name      string    `json:"name"`
        Email     string    `json:"email"`
        StartedAt time.Time `json:"startedAt"` // <==== 这里出错了
        ExpireAt  time.Time `json:"expireAt"`
    }{}

    if err := c.BodyParser(&payload); err != nil {
        return err
    }

    return c.JSON(payload)
}

我收到的时间字符串的格式是"01.01.2001 12:00",但是出现了以下错误:

json: cannot unmarshal "\"01.01.2001 00:00\",\"expireAt\":\"0..." into Go struct field requests.Campaign.startedAt of type time.Time"

英文:

in my project I am using fiber bodyparser to parse json received by my endpoint. I can parse ints and strings, but what if I need to parse Time? Consider the following code:

app.Post(&quot;/post&quot;, func(c *fiber.Ctx) error {
payload := struct {
    Name      string    `json:&quot;name&quot;`
    Email     string    `json:&quot;email&quot;`
    StartedAt time.Time `json:&quot;startedAt&quot;` //&lt;==== error here
    ExpireAt  time.Time `json:&quot;expireAt&quot;`
}{}

if err := c.BodyParser(&amp;payload); err != nil {
    return err
}

return c.JSON(payload)

}

I am receiving a string in 01.01.2001 12:00 format, but getting the following error:

json: cannot unmarshal \&quot;\\\&quot;01.01.2001 00:00\\\&quot;,\\\&quot;expireAt\\\&quot;:\\\&quot;0...\&quot; into Go struct field requests.Campaign.startedAt of type time.Time&quot;

答案1

得分: 1

似乎应该以 ISO 字符串格式传递日期(在 JavaScript 中使用 .toISOString() 或类似的方法)。如果官方文档中能提到这一点就好了。

谢谢。

英文:

Seems that Date should be passed in ISO string format (.toISOString() in js or something). It would be good if it were mentioned in official docs somehow.

Thank you.

答案2

得分: 0

问题出在Go语言上,就像大多数golang的问题一样,这是谷歌方面一个非常令人沮丧但容易解决的问题。

在我的情况下,我只是将其保留为字符串,因为我正在使用一个验证库,然后手动解析为time.Time

这非常令人沮丧,因为你不会期望从一个如此成熟的语言中出现这种愚蠢的行为。

验证库:https://github.com/gookit/validate

我使用了date过滤器(https://pkg.go.dev/github.com/gookit/validate@v1.4.6#IsDate)

英文:

The issue is with Go and as with most golang things, this is such a frustrating but easily solvable issue on google's part.

In my case, I just left it as a string since I was using a validation library and then only manually parsed to time.Time.

It's very frustrating because you'd not expect this stupid behavior from such a matured language.

The validation library: https://github.com/gookit/validate

I used the date filter (https://pkg.go.dev/github.com/gookit/validate@v1.4.6#IsDate)

huangapple
  • 本文由 发表于 2022年5月18日 21:18:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/72289964.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定