douan6931 2016-06-01 00:23
浏览 365
已采纳

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.

  • 写回答

2条回答 默认 最新

  • dougengqiu8031 2016-06-01 01: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条)
编辑
预览

报告相同问题?

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

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

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

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

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

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

客服 返回
顶部