Skip to content

Instantly share code, notes, and snippets.

@petergtz
Last active June 19, 2017 09:56
Show Gist options
  • Save petergtz/e0d049175701086d1759270746812d02 to your computer and use it in GitHub Desktop.
Save petergtz/e0d049175701086d1759270746812d02 to your computer and use it in GitHub Desktop.
A CopyFile function in Go with correct error handling
func CopyFile(dstName, srcName string) (int64, error) {
src, e := os.Open(srcName)
if e != nil {
return 0, errors.New("Error while opening file for reading. Caused by: " + e.Error())
}
dst, e := os.Create(dstName)
if e != nil {
src.Close()
return 0, errors.New("Error while opening file for writing. Caused by: " + e.Error())
}
numBytesWritten, e := io.Copy(dst, src)
if e != nil {
dst.Close()
src.Close()
return 0, errors.New("Error while copying. Caused by: " + e.Error())
}
e = dst.Close()
if e != nil {
src.Close()
return numBytesWritten, errors.New("Error while closing. Caused by: " + e.Error())
}
e = src.Close()
if e != nil {
return numBytesWritten, errors.New("Error while closing. Caused by: " + e.Error())
}
return numBytesWritten, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment