ReadAll from File不能按预期工作

I am trying to create a temporary gzip file and write to the file. The problem is that I am not understanding what is going on with ReadAll. I expected ReadAll to return the bytes written to the file... however there are none. Yet the File.Stat command shows that there is indeed data.

filename := "test"
file, err := ioutil.TempFile("", filename)
if err != nil {
    fmt.Println(err)
}
defer func() {
    if err := os.Remove(file.Name()); err != nil {
        fmt.Println(err)
    }
}()

w := gzip.NewWriter(file)
_, err = w.Write([]byte("hell0"))
if err != nil {
    fmt.Println(err)
}

fileInfo, err := file.Stat()
if err != nil {
    fmt.Println(err)
}
fileBytes, err := ioutil.ReadAll(file)
if err != nil {
    fmt.Println(err)
}
if err := w.Close(); err != nil {
    fmt.Println(err)
}
fmt.Println("SIZE1:", fileInfo.Size())
fmt.Println("SIZE2:", len(fileBytes))

Here is a playground link https://play.golang.org/p/zX8TSCAbRL

Why are there no returned bytes? How do I get the returned bytes?

Close the file before reading it.

From the documentation of gzip:

Write writes a compressed form of p to the underlying io.Writer. The compressed bytes are not necessarily flushed until the Writer is closed.

The solution therefore is to Close both the gzip Writer as well as the underlying io.Writer before attempting to read the number of bytes.

    func main() {
        basename := "test"
        file, err := ioutil.TempFile("", basename)
        tempFilename := file.Name()
        if err != nil {
            fmt.Println(err)
        }
        defer func() {
            if err := os.Remove(file.Name()); err != nil {
                fmt.Println(err)
            }
        }()

        w := gzip.NewWriter(file)
        _, err = w.Write([]byte("hell0"))
        if err != nil {
            fmt.Println(err)
        }

        w.Close()
        file.Close()

        file, err = os.Open(tempFilename)
        fileInfo, err := file.Stat()
        if err != nil {
            fmt.Println(err)
        }
        fileBytes, err := ioutil.ReadAll(file)
        if err != nil {
            fmt.Println(err)
        }
        if err := w.Close(); err != nil {
            fmt.Println(err)
        }
        fmt.Println("SIZE1:", fileInfo.Size())
        fmt.Println("SIZE2:", len(fileBytes))

}

View on Playground.

Yo must seek the start of the file:

_, _ = file.Seek(0, 0)
fileBytes, err := ioutil.ReadAll(file)
if err != nil {
    fmt.Println(err)
}

Check the Playground