Reputation: 7210
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.
Upvotes: 2
Views: 2671
Reputation: 2488
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
}
Upvotes: 2
Reputation: 1145
As per the documentation for gzip.NewReader
, If r does not also implement io.ByteReader, the decompressor may read more data than necessary from r.
For bytes.Reader, A Reader implements the io.Reader, io.ReaderAt, io.WriterTo, io.Seeker, io.ByteScanner, and io.RuneScanner interfaces by reading from a byte slice.
The problem maybe lies in the fact that bytes.Reader
does not implement io.ByteReader
.
Upvotes: 0