Skip to content

Instantly share code, notes, and snippets.

@tomcatzh
Last active April 3, 2024 09:30
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomcatzh/cf8040820962e0f8c04700eb3b2f26be to your computer and use it in GitHub Desktop.
Save tomcatzh/cf8040820962e0f8c04700eb3b2f26be to your computer and use it in GitHub Desktop.
Wrap a reader to a gzip compress reader using gzip writer :-P
func NewGzipReader(source io.Reader) io.Reader {
r, w := io.Pipe()
go func() {
defer w.Close()
zip, err := gzip.NewWriterLevel(w, gzip.BestSpeed)
defer zip.Close()
if err != nil {
w.CloseWithError(err)
}
io.Copy(zip, source)
}()
return r
}
@ReallyLiri
Copy link

Better add err handling also around the io.Copy:

		_, err = io.Copy(zip, source)
		if err != nil {
			w.CloseWithError(err)
		}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment