我正在使用 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 我會在這里重新發明輪子嗎?
1 回答

BIG陽
TA貢獻1859條經驗 獲得超6個贊
您可以創建自定義類型并使用它的BodyTyte結構。
type SpecialDate struct {
time.Time
}
type BodyType struct {
YourDate SpecialDate
}
并寫入UnmarshalJSONforSpecialDate將毫秒解析為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 關注
- 117 瀏覽
添加回答
舉報
0/150
提交
取消