如何设置和解析 body 请求中的时间?

How to set and parse the time inside of a body request?

我正在使用 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,我会在这里重新发明轮子吗?

您可以创建自定义类型并使用它 BodyTyte 结构。

type SpecialDate struct {
    time.Time
}

type BodyType struct {
    YourDate SpecialDate
}

并为 SpecialDate 写入 UnmarshalJSON 以将毫秒解析为 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
}