douan6931
2016-06-01 08:23
浏览 360
已采纳

Golang从字节解压缩gzip.Reader

I have a file struct that holds a body which is just a *bytes.Reader I have two methods on the struct Zip() error and UnZip() error. When I call Zip it should zip the file storing the zipped data in body and I should be able to call UnZip on the same file and store the unzipped data in the body.

The minimal example I have is below in the playground. https://play.golang.org/p/WmZtqtvnyN

I'm able to zip the file just fine and looks like it's doing what it's supposed to do; however, when I try and unzip the file I get unexpected EOF

I've been going at this for hours now. Any help is greatly appreciated.

图片转代码服务由CSDN问答提供 功能建议

我有一个文件结构,该结构包含仅 * bytes.Reader 的主体 我对struct Zip()错误 UnZip()错误有两种方法。 当我调用 Zip 时,应该压缩将压缩数据存储在主体中的文件,并且我应该能够在同一文件上调用 UnZip 并将未压缩的数据存储在主体中。

我下面的最小示例在操场上。 https://play.golang.org/p/WmZtqtvnyN

我可以很好地压缩文件,并且看起来像它应该做的那样; 但是,当我尝试解压缩文件时,得到意外的EOF

,我已经花了几个小时了。 任何帮助将不胜感激。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • dougengqiu8031 2016-06-01 09:33
    最佳回答

    I believe you should close gzip writer before geting bytes from the underlying buffer.

    func (f *File) Zip() error {
        buff := bytes.NewBuffer(nil)
    
        writer := gzip.NewWriter(buff)
        defer writer.Close()
    
        _, err := f.Body.WriteTo(writer)
        if err != nil {
            return err
        }
    
        writer.Close() // I have added this line
    
        f.Body = bytes.NewReader(buff.Bytes())
        f.Name = fmt.Sprintf("%s.gz", f.Name)
        return nil
    }
    
    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题