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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器