Reading from and writing to a file without passing around filename 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?
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