-
Notifications
You must be signed in to change notification settings - Fork 145
/
Copy pathredispubsub.go
146 lines (121 loc) · 3.01 KB
/
redispubsub.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
package main
import (
"log"
"net/http"
"sync"
"github.com/garyburd/redigo/redis"
"github.com/gorilla/websocket"
uuid "github.com/satori/go.uuid"
)
var (
gStore *Store
gPubSubConn *redis.PubSubConn
gRedisConn = func() (redis.Conn, error) {
return redis.Dial("tcp", ":6379")
}
)
func init() {
gStore = &Store{
Users: make([]*User, 0, 1),
}
}
// User holds a websocket connection and unique ID
type User struct {
ID string
conn *websocket.Conn
}
// Store holds the collection of users connected through websocket
type Store struct {
Users []*User
sync.Mutex
}
// Message gets exchanged between users through redis pub/sub messaging
// Users may have websocket connections to different nodes and stored in
// different instances of this application
type Message struct {
DeliveryID string `json:"id"`
Content string `json:"content"`
}
func (s *Store) newUser(conn *websocket.Conn) *User {
u := &User{
ID: uuid.NewV4().String(),
conn: conn,
}
if err := gPubSubConn.Subscribe(u.ID); err != nil {
panic(err)
}
s.Lock()
defer s.Unlock()
s.Users = append(s.Users, u)
return u
}
var serverAddress = ":8080"
func main() {
gRedisConn, err := gRedisConn()
if err != nil {
panic(err)
}
defer gRedisConn.Close()
gPubSubConn = &redis.PubSubConn{Conn: gRedisConn}
defer gPubSubConn.Close()
// deliver messages runs on another goroutine to binded to redis pub/sub
// messaging responsible of delivering messages to users through websocket conn
go deliverMessages()
http.HandleFunc("/ws", wsHandler)
log.Printf("server started at %s\n", serverAddress)
log.Fatal(http.ListenAndServe(serverAddress, nil))
}
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func wsHandler(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("upgrader error %s\n" + err.Error())
return
}
u := gStore.newUser(conn)
log.Printf("user %s joined\n", u.ID)
for {
var m Message
if err := u.conn.ReadJSON(&m); err != nil {
log.Printf("error on ws. message %s\n", err)
}
if c, err := gRedisConn(); err != nil {
log.Printf("error on redis conn. %s\n", err)
} else {
c.Do("PUBLISH", m.DeliveryID, string(m.Content))
}
}
}
func deliverMessages() {
for {
switch v := gPubSubConn.Receive().(type) {
case redis.Message:
gStore.findAndDeliver(v.Channel, string(v.Data))
case redis.Subscription:
log.Printf("subscription message: %s: %s %d\n", v.Channel, v.Kind, v.Count)
case error:
log.Println("error pub/sub on connection, delivery has stopped")
return
}
}
}
func (s *Store) findAndDeliver(userID string, content string) {
m := Message{
Content: content,
}
for _, u := range s.Users {
if u.ID == userID {
if err := u.conn.WriteJSON(m); err != nil {
log.Printf("error on message delivery through ws. e: %s\n", err)
} else {
log.Printf("user %s found at our store, message sent\n", userID)
}
return
}
}
log.Printf("user %s not found at our store\n", userID)
}