我正在使用 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)}我的意圖是制作一個(gè)像這樣的請(qǐng)求正文:{ YourDate: 1589887669644}然后服務(wù)器自動(dòng)獲取我提供的 Int,并將該日期解析為日期格式 time.Time,有沒有一種干凈的方法可以做到這一點(diǎn)?如果我嘗試編寫自己的函數(shù)來接收 int64 類型的“YourDate”并解析為 time.Time 我會(huì)在這里重新發(fā)明輪子嗎?
1 回答

BIG陽
TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以創(chuàng)建自定義類型并使用它的BodyTyte結(jié)構(gòu)。
type SpecialDate struct {
time.Time
}
type BodyType struct {
YourDate SpecialDate
}
并寫入U(xiǎn)nmarshalJSONforSpecialDate將毫秒解析為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
}
- 1 回答
- 0 關(guān)注
- 109 瀏覽
添加回答
舉報(bào)
0/150
提交
取消