-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy patherror.go
121 lines (101 loc) · 2.1 KB
/
error.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
// reference : https://coolshell.cn/articles/21140.html
// see more:
// https://github.com/pkg/errors
// https://pkg.go.dev/errors
// 一些不错的实践:https://lailin.xyz/post/go-training-03.html
package idiom
import (
"encoding/binary"
"io"
)
type Point struct {
PI float64
Uate uint8
Mine [3]byte
Too uint16
}
type Person struct {
Name [10]byte
Age uint8
Weight uint8
err error
}
// 1. Error Check Hell
func parse(r io.Reader) (*Point, error) {
var p Point
if err := binary.Read(r, binary.LittleEndian, &p.PI); err != nil {
return nil, err
}
if err := binary.Read(r, binary.LittleEndian, &p.Uate); err != nil {
return nil, err
}
if err := binary.Read(r, binary.LittleEndian, &p.Mine); err != nil {
return nil, err
}
if err := binary.Read(r, binary.LittleEndian, &p.Too); err != nil {
return nil, err
}
return &p, nil
}
// 2. 使用函数式编程方式
func parse2(r io.Reader) (*Point, error) {
var p Point
var err error
read := func(data interface{}) {
if err != nil {
return
}
err = binary.Read(r, binary.LittleEndian, data)
}
read(&p.PI)
read(&p.Uate)
read(&p.Mine)
read(&p.Too)
if err != nil {
return &p, err
}
return &p, nil
}
// 3. 清除内部函数
type Reader struct {
r io.Reader
err error
}
func (r *Reader) read(data interface{}) {
if r.err == nil {
r.err = binary.Read(r.r, binary.LittleEndian, data)
}
}
func parse3(input io.Reader) (*Point, error) {
var p Point
r := Reader{r: input}
r.read(&p.PI)
r.read(&p.Uate)
r.read(&p.Mine)
r.read(&p.Too)
if r.err != nil {
return nil, r.err
}
return &p, nil
}
// 4. 流式接口 Fluent Interface 长度不够,少一个 Weight 字段
func (p *Person) read(input io.Reader, data interface{}) {
if p.err == nil {
p.err = binary.Read(input, binary.BigEndian, data)
}
}
func (p *Person) ReadName(input io.Reader) *Person {
p.read(input, &p.Name)
return p
}
func (p *Person) ReadAge(input io.Reader) *Person {
p.read(input, &p.Age)
return p
}
func (p *Person) ReadWeight(input io.Reader) *Person {
p.read(input, &p.Weight)
return p
}
func (p *Person) Print() *Person {
return p
}