I was looking for a way to write to and then read from a file in different parts of my code, without passing the filename around and without consumers needing to know it was coming from a file.
I came up with this FilePipe
based on io.Pipe
:
package pipe
import (
"io"
"os"
)
func FilePipe(name string) (*io.PipeReader, *io.PipeWriter) {
inr, inw := io.Pipe()
outr, outw := io.Pipe()
go func() {
// Open the file for writing
f, err := os.Create(name)
if err != nil {
outw.CloseWithError(err)
return
}
// Copy the input to the file
_, err = io.Copy(f, inr)
f.Close()
if err != nil {
outw.CloseWithError(err)
return
}
// Open the file for reading
f, err = os.Open(name)
if err != nil {
outw.CloseWithError(err)
return
}
// Copy the file to the output
_, err = io.Copy(outw, f)
f.Close()
if err != nil {
outw.CloseWithError(err)
return
}
outw.Close()
}()
return outr, inw
}
What do you think? Is there a better way to do this?
os.File.Close
if the file was written to. An error writing a file may not get reported until the file gets closed. \$\endgroup\$ – Dave C Aug 22 '19 at 15:47