小编典典

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

go

我最近一直在玩Go,它很棒。在浏览文档和博客文章之后,我似乎无法弄清楚的事情是如何将time.Time类型格式化为我想要的格式,json.NewEncoder.Encode

这是一个最小的代码示例:

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
    }
}

理想情况下,我想发送一个请求并以类似的方式获取“戳记”字段,May 15, 2014而不是2014-05-16T08:28:06.801064-04:00

但是我不确定如何,我知道我可以添加json:stamp到文档类型声明中以使用名称戳而不是戳来编码字段,但是我不知道这些类型的东西叫什么,所以我我什至不确定要在Google上查找什么,以了解其中是否还有某种格式设置选项。

是否有人链接到示例或优质文档页面上有关这些类型标记(或称为它们的名称)主题的链接,或者我如何告诉JSON编码器处理time.Time字段?

仅供参考,我查看了以下页面:这里这里,当然还有官方文档


阅读 325

收藏
2020-07-02

共1个答案

小编典典

您可以做的是,将time.Time包装为您自己的自定义类型,并使其实现Marshaler接口:

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

因此,您要做的是:

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
}

并制作文件:

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

并使您的初始化看起来像:

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

就是这样。如果您想拆封,也可以使用该Unmarshaler界面。

2020-07-02