Golang Bufio writer .Flush() does not write small data when big buffer size (example 4096(standard size)*2)
package main
import (
"log"
"os"
"bufio"
)
func main() {
file, err := os.Create("test")
defer file.Close()
w := bufio.NewWriter(file)
w = bufio.NewWriterSize(
w,
4096*2,
)
bytesAvailable := w.Available()
log.Printf("Available %v\n", bytesAvailable)
bw, _ := w.Write(
[]byte("A"),
)
log.Printf("written bytes: %v\n", bw)
bytesAvailable = w.Available()
log.Printf("Available: %v\n", bytesAvailable)
buf := w.Buffered()
log.Printf("buffered: %d\n", buf)
err = w.Flush()
if err != nil {
log.Fatal(err)
}
}
When I use the standard size or I write more data it works as expected.
The problem is that the application has two layers of bufio writers:
w := bufio.NewWriter(file)
w = bufio.NewWriterSize(
w,
4096*2,
)
One bufio.Writer wraps the other. The application flushes the outer bufio.Writer, but there's no code that flushes the inner bufio.Writer. Change the code to use a single bufio.Writer and the program will work as expected.
w := bufio.NewWriterSize(
file,
4096*2,
)
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