我正在与Gin Gonic一起使用Go,我有类似以下内容:
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。我会在这里重新发明轮子吗?
最佳答案
您可以创建一个自定义类型并使用BodyTyte
结构。
type SpecialDate struct {
time.Time
}
type BodyType struct {
YourDate SpecialDate
}
并将
UnmarshalJSON
写入SpecialDate
以将毫秒解析为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
}
关于go - 如何设置和解析正文请求中的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61889987/