dsfjk44656 2019-03-25 23: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 23: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]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多