dsfjk44656 2019-03-25 15:08
浏览 154
已采纳

如何将对象流式传输到gzip json?

Currently the way to convert an object to json and gzip it is:

jsonBytes, _ := json.Marshal(payload)
//gzip json
var body bytes.Buffer
g := gzip.NewWriter(&body)
g.Write(jsonBytes)
g.Close()

This results in an intermediate large byte buffer jsonBytes, whose only purpose is to be then converted into gzipped buffer.

Is there any way to stream the marshalling of the payload object so it comes out gzipped in the first place?

  • 写回答

1条回答 默认 最新

  • dqthn68688 2019-03-25 15:16
    关注

    Yes, you may use json.Encoder to stream the JSON output, and similarly json.Decoder to decode a streamed JSON input. They take any io.Writer and io.Reader to write the JSON result to / read from, including gzip.Writer and gzip.Reader.

    For example:

    var body bytes.Buffer
    w := gzip.NewWriter(&body)
    
    enc := json.NewEncoder(w)
    
    payload := map[string]interface{}{
        "one": 1, "two": 2,
    }
    if err := enc.Encode(payload); err != nil {
        panic(err)
    }
    if err := w.Close(); err != nil {
        panic(err)
    }
    

    To verify that it works, this is how we can decode it:

    r, err := gzip.NewReader(&body)
    if err != nil {
        panic(err)
    }
    dec := json.NewDecoder(r)
    payload = nil
    if err := dec.Decode(&payload); err != nil {
        panic(err)
    }
    
    fmt.Println("Decoded:", payload)
    

    Which will output (try it on the Go Playground):

    Decoded: map[one:1 two:2]
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部