This is how I am using gzip writer.
var b bytes.Buffer
gz := gzip.NewWriter(&b)
if _, err := gz.Write([]byte(data)); err != nil {
panic(err)
}
/*
if err := gz.Flush(); err != nil {
panic(err)
}
*/
if err := gz.Close(); err != nil {
panic(err)
}
playground link https://play.golang.org/p/oafHItGOlDN
Clearly, Flush + Close
and just Close
are giving different results.
Docs for the compress/gzip
package says:
func (z *Writer) Close() error
Close closes the Writer by flushing any unwritten data to the underlying io.Writer and writing the GZIP footer. It does not close the underlying io.Writer.
What flushing is this doc talking about? Why do you need Flush
function at all if Close
is enough? Why doesn't Close
call Flush
?
Closing does cause a flush. When you call Flush
and then Close
, the stream is flushed twice, which causes an additional chunk to be output, which uses 5 bytes to code 0 bytes of data. Both streams encode the same data, but one of them is wasteful.
As for why you would use Flush, the explanation is right there in the documentation for Flush. Sometimes you're not done writing, but you need to ensure that all of the data that you've written up to this point is readable by the client, before additional data is available. At those points, you flush the stream. You only close when there will be no more data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With