-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcloser.go
More file actions
57 lines (49 loc) · 1.67 KB
/
closer.go
File metadata and controls
57 lines (49 loc) · 1.67 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
55
56
57
package runnable
import (
"context"
)
// Closer returns a runnable that calls Close on context cancellation.
// There is no timeout on the call to Close.
func Closer(c interface{ Close() }) Runnable {
return &closer{"closer/" + runnableName(c), func(_ context.Context) error {
c.Close()
return nil
}}
}
// CloserErr returns a runnable that calls Close on context cancellation.
// There is no timeout on the call to Close.
func CloserErr(c interface{ Close() error }) Runnable {
return &closer{"closer/" + runnableName(c), func(_ context.Context) error {
return c.Close()
}}
}
// CloserCtx returns a runnable that calls Close on context cancellation.
// The context passed to Close is not cancelled, so Close can perform graceful cleanup.
// There is no timeout on the call to Close.
func CloserCtx(c interface{ Close(context.Context) }) Runnable {
return &closer{"closer/" + runnableName(c), func(ctx context.Context) error {
c.Close(ctx)
return nil
}}
}
// CloserCtxErr returns a runnable that calls Close on context cancellation.
// The context passed to Close is not cancelled, so Close can perform graceful cleanup.
// There is no timeout on the call to Close.
func CloserCtxErr(c interface{ Close(context.Context) error }) Runnable {
return &closer{"closer/" + runnableName(c), func(ctx context.Context) error {
return c.Close(ctx)
}}
}
type closer struct {
name string
closeFn func(context.Context) error
}
func (c *closer) runnableName() string { return c.name }
func (c *closer) Run(ctx context.Context) error {
<-ctx.Done()
err := c.closeFn(context.WithoutCancel(ctx))
if err != nil {
return &RunnableError{"closer: Close() returned an error", err}
}
return nil
}