Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you need `Flush` at all if `Close` is enough?

Tags:

go

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?

like image 836
Pratik Deoghare Avatar asked Mar 08 '18 05:03

Pratik Deoghare


1 Answers

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.

like image 138
hobbs Avatar answered Nov 15 '22 08:11

hobbs