-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathcloser.go
71 lines (62 loc) · 1.53 KB
/
closer.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
package plz
import (
"fmt"
"github.com/v2pro/plz/countlog"
"io"
"runtime"
)
type MultiError []error
func (errs MultiError) Error() string {
return "multiple errors"
}
func MergeErrors(errs ...error) error {
var nonNilErrs []error
for _, err := range errs {
if err != nil {
nonNilErrs = append(nonNilErrs, err)
}
}
if len(nonNilErrs) == 0 {
return nil
}
return MultiError(nonNilErrs)
}
func Close(resource io.Closer, properties ...interface{}) error {
err := resource.Close()
if err != nil {
_, file, line, _ := runtime.Caller(1)
closedAt := fmt.Sprintf("%s:%d", file, line)
properties = append(properties, "err", err)
countlog.Error("event!close "+closedAt, properties...)
return err
}
return nil
}
func CloseAll(resources []io.Closer, properties ...interface{}) error {
var errs []error
for _, resource := range resources {
err := resource.Close()
if err != nil {
_, file, line, _ := runtime.Caller(1)
closedAt := fmt.Sprintf("%s:%d", file, line)
properties = append(properties, "err", err)
countlog.Error("event!CloseAll called from "+closedAt, properties...)
errs = append(errs, err)
}
}
if len(errs) == 0 && len(properties) > 0 {
_, file, line, _ := runtime.Caller(1)
closedAt := fmt.Sprintf("%s:%d", file, line)
countlog.Debug("event!CloseAll called from "+closedAt, properties...)
}
return MergeErrors(errs...)
}
type funcResource struct {
f func() error
}
func (res funcResource) Close() error {
return res.f()
}
func WrapCloser(f func() error) io.Closer {
return &funcResource{f}
}