Last active
June 19, 2017 09:56
-
-
Save petergtz/e0d049175701086d1759270746812d02 to your computer and use it in GitHub Desktop.
A CopyFile function in Go with correct error handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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