forked from hetiansu5/work
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcontext_hook.go
More file actions
65 lines (57 loc) · 1.32 KB
/
context_hook.go
File metadata and controls
65 lines (57 loc) · 1.32 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
58
59
60
61
62
63
64
65
package work
import (
"context"
"time"
)
// ContextHook represents a hook context
type ContextHook struct {
start time.Time
Ctx context.Context
Topic string // topic
Args []interface{}
ExecuteTime time.Duration
Err error // execute error
}
// NewContextHook return context for hook
func NewContextHook(ctx context.Context, topic string, args []interface{}) *ContextHook {
return &ContextHook{
start: time.Now(),
Ctx: ctx,
Topic: topic,
Args: args,
}
}
// End finish the hook invoke
func (c *ContextHook) End(err error) {
c.Err = err
c.ExecuteTime = time.Since(c.start)
}
// Hook represents a hook behaviour
type Hook interface {
BeforeProcess(c *ContextHook) error
AfterProcess(c *ContextHook) error
}
// AddHook adds a Hook
func (j *Job) AddHook(hooks ...Hook) {
j.pdHooks = append(j.pdHooks, hooks...)
}
// BeforeProcess invoked before execute the process
func (j *Job) BeforeProcess(c *ContextHook) error {
for _, hk := range j.pdHooks {
if err := hk.BeforeProcess(c); err != nil {
return err
}
}
return nil
}
// AfterProcess invoked after execute the process
func (j *Job) AfterProcess(c *ContextHook) error {
firstErr := c.Err
for _, hk := range j.pdHooks {
err := hk.AfterProcess(c)
if err != nil && firstErr == nil {
firstErr = err
}
}
return firstErr
}