duannei1477 2015-12-15 08:15
浏览 179
已采纳

在Golang中遇到gzip.Reader遇到问题

Why doesn't this work? (sorry for some reason I cannot get a share button on Go Playground).

package main

import (
    "bytes"
    "compress/gzip"
    "fmt"
    "io"
)

func main() {
    // ENCODE
    data := []byte{1, 2, 3, 4, 5, 6, 7}
    bb0 := bytes.NewBuffer(data)
    byts := bb0.Bytes()
    fmt.Printf("data = % x
", data)
    fmt.Printf("byte buffer bb0 contains = % x
", byts)
    bb1 := new(bytes.Buffer)
    w := gzip.NewWriter(bb1)
    s1, err := w.Write(byts)
    fmt.Printf("%d bytes written using gzip writer, err = %v
", s1, err)
    byts = bb1.Bytes()
    fmt.Printf("byte buffer bb1 contains = % x
", byts)
    // DECODE
    r, err := gzip.NewReader(bb1)
    bb2 := new(bytes.Buffer)
    s2, err := io.Copy(bb2, r)
    r.Close()
    fmt.Printf("%d bytes copied from gzip reader, err = %v
", s2, err)
    byts = bb2.Bytes()
    fmt.Printf("byte buffer bb2 contains = % x
", byts)
}

The output I get

data = 01 02 03 04 05 06 07
byte buffer bb0 contains = 01 02 03 04 05 06 07
7 bytes written using gzip writer, err = <nil>
byte buffer bb1 contains = 1f 8b 08 00 00 09 6e 88 00 ff
0 bytes copied from gzip reader, err = unexpected EOF
byte buffer bb2 contains = 

The reader doesn't seem to be doing anything, what am I doing wrong?

  • 写回答

1条回答 默认 最新

  • douzhi7082 2015-12-15 08:35
    关注

    Probably it doesn't work because you didn't close the gzip writer and so the gzipped data was never flushed to the underlying writer (for which you are using a bytes.Buffer), or at least it wasn't finalized.

    You need to w.Close() the gzip writer after writing.

    Alternatively, it could be that the bytes.Buffer needs to be seeked to zero before attempting to read from it, as it might be that the reader is trying to read from the end of it.

    Also what you're doing is inefficient, I'd suggest you use: https://github.com/AlasdairF/Custom

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

报告相同问题?

悬赏问题

  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多