【问题标题】:How to set and parse the time inside of a body request?如何设置和解析正文请求中的时间?
【发布时间】:2020-05-19 20:16:02
【问题描述】:

我正在使用 Go 和 Gin Gonic,我有这样的东西:

import (
  "time"
)

type BodyType struct {
  YourDate: time.Time
}

func doThingWithPost(c *gin.Context) {
  var theBody BodyType
  c.BindJSON(&theBody)

  c.JSON(http.StatusOK, gin.H{"data": theBody.YourDate})
}

func main() {
    r.POST("/", doThingWithPost)
}

我的意图是制作一个像这样的请求正文:

{
  YourDate: 1589887669644
}

然后服务器会自动获取我提供的 Int,并将该日期解析为日期格式 time.Time,有没有一种干净的方法可以做到这一点?如果我尝试编写自己的函数来接收 int64 类型的“YourDate”并解析为 time.Time 我会在这里重新发明轮子吗?

【问题讨论】:

  • 如果你的目标是输出当时的Unix时间,为什么不直接调用Unix()呢? stackoverflow.com/q/35688419/13860
  • @Flimzy 一些版本设置了这个标题......抱歉造成混乱
  • @Flimzy 这还有另一个问题,如果您这样做,请求中的类型验证将委托给我自己的解析器...但是如果您在请求中发送字符串而不是 int 语言本身自己解决了这个类型的验证...

标签: go http-post go-gin


【解决方案1】:

您可以创建一个自定义类型并使用它BodyTyte struct。

type SpecialDate struct {
    time.Time
}

type BodyType struct {
    YourDate SpecialDate
}

并为SpecialDateUnmarshalJSON以将毫秒解析为time.Time

func (sd *SpecialDate) UnmarshalJSON(input []byte) error {
    millis, err := strconv.ParseInt(string(input), 10, 64)
    if err != nil {
        panic(err)
    }
    tm := time.Unix(0, millis*int64(time.Millisecond))
    sd.Time = tm
    return nil
}

【讨论】:

    猜你喜欢
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 2021-07-09
    • 2022-07-18
    • 1970-01-01
    • 2017-06-01
    相关资源
    最近更新 更多