user2108258
user2108258

Reputation: 843

Read contents from what io.Writer writes

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")
}

Upvotes: 4

Views: 2666

Answers (1)

Mr_Pink
Mr_Pink

Reputation: 109347

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)

Upvotes: 6

Related Questions