I would like to copy a file using pure Go, emulating the behavior of cp -p.
My copy function currently looks like:
// copy creates a copy of the file located at `dst` at `src`.
func copyFile(src, dst string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return err
}
_, err = io.Copy(out, in)
if err != nil {
out.Close()
return err
}
return out.Close()
}
which will create dst owned by whoever is running the process. Instead, I would like to keep the owner and permissions of src, i.e. what I get from:
// copy creates a copy of the file located at `dst` at `src`.
func copyFile(src, dst string) error {
cmd := exec.Command("cp", "-p", src, dst)
return cmd.Run()
}
but without having to call through to system commands (for portability). Everything I tried ended up calling through to something else. Is this possible to do in Go?