/
pubsub.go
79 lines (58 loc) · 1.22 KB
/
pubsub.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
package pubsub
import (
"github.com/go-redis/redis"
"strings"
)
type Writer struct {
Channel string
Client *redis.Client
Pubsub *redis.PubSub
}
func NewWriter(channel string) (*Writer, error) {
return newwriter("localhost:6379", "", 0, channel)
}
/*
func NewWriter(addr string, pswd string, db int, channel string) (*Writer, error) {
return newwriter(addr, pswd, db, channel)
}
*/
func newwriter(addr string, pswd string, db int64, channel string) (*Writer, error) {
client := redis.NewClient(&redis.Options{
Addr: addr,
Password: pswd,
DB: db,
})
_, err := client.Ping().Result()
if err != nil {
return nil, err
}
pubsub, err := client.Subscribe(channel)
if err != nil {
return nil, err
}
defer pubsub.Close()
w := Writer{
Channel: channel,
Client: client,
Pubsub: pubsub,
}
return &w, nil
}
func (w Writer) WriteString(s string) (n int64, err error) {
r := strings.NewReader(s)
return r.WriteTo(w)
}
func (w Writer) Write(p []byte) (n int, err error) {
var msg string
msg = string(p[:])
err = w.Client.Publish(w.Channel, msg).Err()
if err != nil {
return 0, err
}
count := len(msg)
return count, nil
}
func (w Writer) Close() error {
w.Pubsub.Close()
return nil
}