-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathevents.go
58 lines (49 loc) · 1.03 KB
/
events.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
package goqless
import (
"fmt"
"github.com/garyburd/redigo/redis"
)
type Events struct {
conn redis.Conn
ch chan interface{}
psc *redis.PubSubConn
host string
port string
}
func NewEvents(host, port string) *Events {
return &Events{host: host, port: port}
}
func (e *Events) Listen() (chan interface{}, error) {
var err error
e.conn, err = redis.Dial("tcp", fmt.Sprintf("%s:%s", e.host, e.port))
if err != nil {
return nil, err
}
e.psc = &redis.PubSubConn{e.conn}
e.ch = make(chan interface{}, 1)
go func() {
for {
val := e.psc.Receive()
if v, ok := val.(error); ok {
e.ch <- v
close(e.ch)
break
}
e.ch <- val
}
}()
for _, i := range []string{"canceled", "completed", "failed", "popped", "stalled", "put", "track", "untrack"} {
err := e.psc.Subscribe(i)
if err != nil {
close(e.ch)
return nil, err
}
}
return e.ch, nil
}
func (e *Events) Unsubscribe() {
if e.psc != nil {
e.psc.Unsubscribe()
e.psc.Close()
}
}