2

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 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

It actually does implement io.ByteReader because io.ByteScanner is a io.ByteReader too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.