forked from ripple-shit/api
/
multi.go
57 lines (50 loc) · 1.17 KB
/
multi.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
package websockets
import (
"encoding/json"
"fmt"
"sync"
)
// SubscribeMultiMatches subscribes to receiving information from completed
// games in multiplayer matches.
func SubscribeMultiMatches(c *conn, message incomingMessage) {
multiSubscriptionsMtx.Lock()
var found bool
for _, el := range multiSubscriptions {
if el.ID == c.ID {
found = true
break
}
}
// if it was not found, we need to add it
if !found {
multiSubscriptions = append(multiSubscriptions, c)
}
multiSubscriptionsMtx.Unlock()
c.WriteJSON(TypeSubscribedToMultiMatches, nil)
}
var multiSubscriptions []*conn
var multiSubscriptionsMtx = new(sync.RWMutex)
func matchRetriever() {
ps, err := red.Subscribe("api:mp_complete_match")
if err != nil {
fmt.Println(err)
}
for {
msg, err := ps.ReceiveMessage()
if err != nil {
fmt.Println(err.Error())
return
}
go handleNewMultiGame(msg.Payload)
}
}
func handleNewMultiGame(payload string) {
defer catchPanic()
multiSubscriptionsMtx.RLock()
cp := make([]*conn, len(multiSubscriptions))
copy(cp, multiSubscriptions)
multiSubscriptionsMtx.RUnlock()
for _, el := range cp {
el.WriteJSON(TypeNewMatch, json.RawMessage(payload))
}
}