亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何設置和解析正文請求中的時間?

如何設置和解析正文請求中的時間?

Go
富國滬深 2022-06-06 14:43:41
我正在使用 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

}


查看完整回答
反對 回復 2022-06-06
  • 1 回答
  • 0 關注
  • 117 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號