Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read contents from what io.Writer writes

Tags:

io

go

There's a library that exports a file but I'd like to capture the contents of the file. I'd like to pass a writer to the library and be able to read what the writer wrote to the file. Eventually i want to augment the library to skip writing this file. Is this possible with io.Copy or io.Pipe?

The library code creates a *File and uses this handle as an io.Writer. I tried using io.Copy but only 0 bytes were read.

func TestFileCopy(t *testing.T) {

codeFile, err := os.Create("test.txt")
if err != nil {
    t.Error(err)
}
defer codeFile.Close()
codeFile.WriteString("Hello World")
n, err := io.Copy(os.Stdout, codeFile)
if err != nil {
    t.Error(err)
}
log.Println(n, "bytes")
}
like image 902
user2108258 Avatar asked Oct 22 '25 02:10

user2108258


1 Answers

If you want to capture the bytes as they are written, use an io.MultiWriter with a bytes.Buffer as the second writer.

var buf bytes.Buffer
w := io.MultiWriter(codeFile, &buf)

or to see the file on stdout as it's written:

w := io.MultiWriter(codeFile, os.Stdout)

Otherwise, if you want to re-read the same file, you need to seek back to the start after writing:

codeFile.Seek(0, 0)
like image 78
JimB Avatar answered Oct 23 '25 17:10

JimB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!