-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
47 lines (41 loc) · 949 Bytes
/
main.go
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
// In Go, errors are values. That means they are not special and you can program
// them. Here is one programming technique for avoiding repetitive error
// handling. Adapted from https://go.dev/blog/errors-are-values.
package main
import (
"fmt"
"io"
"os"
)
type errReader struct {
r io.Reader
err error
}
func (er *errReader) read(buf []byte) {
// read becomes a no-op as soon as an error occurs
if er.err != nil {
return
}
_, er.err = er.r.Read(buf)
}
func main() {
filename := "/etc/passwd"
if len(os.Args) > 1 {
filename = os.Args[1]
}
f, err := os.Open(filename)
if err != nil {
fmt.Fprintf(os.Stderr, "errgo: %v\n", err)
os.Exit(1)
}
defer f.Close()
buf := make([]byte, 9)
er := &errReader{r: f}
er.read(buf[0:3]) // We do not
er.read(buf[3:6]) // handle error
er.read(buf[6:9]) // for each call.
if er.err != nil {
fmt.Fprintf(os.Stderr, "errgo: reading %s: %v\n", filename, er.err)
os.Exit(1)
}
}