-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandle.go
More file actions
54 lines (43 loc) · 1.15 KB
/
handle.go
File metadata and controls
54 lines (43 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
Package handle provides a dead-simple function to panic on error.
Writing Go involves many error checks:
func CopyFile(dstName, srcName string) {
src, err := os.Open(srcName)
if err != nil {
// Handle this somehow...
}
defer src.Close()
dst, err := os.Create(dstName)
if err != nil {
// Handle this somehow...
}
defer dst.Close()
written, err := io.Copy(dst, src)
if err != nil {
// Handle this somehow...
}
}
For production software this is absolutely essential and despite being verbose
it is great design. But it hurts for simple scripting tasks where we would
prefer that it simply panic, as python/java/etc would.
So let's just tell it to handle it for us:
func CopyFile(dstName, srcName string) {
src, err := os.Open(srcName)
handle.Err(err)
defer src.Close()
dst, err := os.Create(dstName)
handle.Err(err)
defer dst.Close()
written, err := io.Copy(dst, src)
handle.Err(err)
}
That is the purpose of this simple package.
*/
package handle
// Err is the key function of the handle package. If err is nil, it does
// nothing. If it is not nil, it panics.
func Err(err error) {
if err != nil {
panic(err)
}
}