\$\begingroup\$
\$\endgroup\$
4
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?
200_success
145k22 gold badges190 silver badges478 bronze badges
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
you could use a teereader:
inr, inw := io.Pipe()
f, _ := os.Create(name)
tr := io.TeeReader(inr, f)
return tr, inw
use this code in go routine and handle errors
Vogel612
25.5k7 gold badges59 silver badges141 bronze badges
answered Jul 27, 2018 at 7:22
-
3\$\begingroup\$ For a go noob like me: how does this work, why is it better than the solution in the question? \$\endgroup\$Vogel612– Vogel6122018年07月27日 08:46:44 +00:00Commented Jul 27, 2018 at 8:46
lang-golang
os.File.Close
if the file was written to. An error writing a file may not get reported until the file gets closed. \$\endgroup\$