英文:
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("/post", func(c *fiber.Ctx) error {
payload := struct {
Name string `json:"name"`
Email string `json:"email"`
StartedAt time.Time `json:"startedAt"` //<==== error here
ExpireAt time.Time `json:"expireAt"`
}{}
if err := c.BodyParser(&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 \"\\\"01.01.2001 00:00\\\",\\\"expireAt\\\":\\\"0...\" into Go struct field requests.Campaign.startedAt of type time.Time"
答案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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论