dongqieli4164 2014-05-16 12:53
浏览 63
已采纳

在Golang中以外发JSON格式设置时间戳?

I've been playing with Go recently and it's awesome. The thing I can't seem to figure out (after looking through documentation and blog posts) is how to get the time.Time type to format into whatever format I'd like when it's encoded by json.NewEncoder.Encode

Here's a minimal Code example:

package main

type Document struct {
    Name        string
    Content     string
    Stamp       time.Time
    Author      string
}

func sendResponse(data interface{}, w http.ResponseWriter, r * http.Request){
     _, err := json.Marshal(data)
    j := json.NewEncoder(w)
    if err == nil {
        encodedErr := j.Encode(data)
        if encodedErr != nil{
            //code snipped
        }
    }else{
       //code snipped
    }
}

func main() {
    http.HandleFunc("/document", control.HandleDocuments)
    http.ListenAndServe("localhost:4000", nil)
}

func HandleDocuments(w http.ResponseWriter,r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    w.Header().Set("Access-Control-Allow-Origin", "*")

    switch r.Method {
        case "GET": 
            //logic snipped
            testDoc := model.Document{"Meeting Notes", "These are some notes", time.Now(), "Bacon"}    
            sendResponse(testDoc, w,r)
            }
        case "POST":
        case "PUT":
        case "DELETE":
        default:
            //snipped
    }
}

Ideally, I'd like to send a request and get the Stamp field back as something like May 15, 2014 and not 2014-05-16T08:28:06.801064-04:00

But I'm not really sure how, I know I can add json:stamp to the Document type declaration to get the field to be encoded with the name stamp instead of Stamp, but I don't know what those types of things are called, so I'm not even sure what to google for to find out if there is some type of formatting option in that as well.

Does anyone have a link to the an example or good documentation page on the subject of those type mark ups (or whatever they're called) or on how I can tell the JSON encoder to handle time.Time fields?

Just for reference, I have looked at these pages: here and here and of course, at the official docs

  • 写回答

4条回答 默认 最新

  • dongshijiao2363 2014-05-16 13:06
    关注

    What you can do is, wrap time.Time as your own custom type, and make it implement the Marshaler interface:

    type Marshaler interface {
        MarshalJSON() ([]byte, error)
    }
    

    So what you'd do is something like:

    type JSONTime time.Time
    
    func (t JSONTime)MarshalJSON() ([]byte, error) {
        //do your serializing here
        stamp := fmt.Sprintf("\"%s\"", time.Time(t).Format("Mon Jan _2"))
        return []byte(stamp), nil
    }
    

    and make document:

    type Document struct {
        Name        string
        Content     string
        Stamp       JSONTime
        Author      string
    }
    

    and have your intialization look like:

     testDoc := model.Document{"Meeting Notes", "These are some notes", JSONTime(time.Now()), "Bacon"}    
    

    And that's about it. If you want unmarshaling, there is the Unmarshaler interface too.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)