-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpromises.go
More file actions
112 lines (97 loc) · 2.3 KB
/
promises.go
File metadata and controls
112 lines (97 loc) · 2.3 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
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
package main
import (
"fmt"
"github.com/RedisMPX/go-mpx"
"github.com/gomodule/redigo/redis"
"github.com/gorilla/websocket"
"log"
"net/http"
"time"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true },
}
func main() {
// rClient := redis.NewClient(&redis.Options{
// Addr: "localhost:6379", // use default Addr
// Password: "", // no password set
// DB: 0, // use default DB
// })
connBuilder := func() (redis.Conn, error) {
return redis.Dial("tcp", ":6379")
}
multiplexer := mpx.New(connBuilder)
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
sub := multiplexer.NewPromiseSubscription("p:")
sub.WaitForActivation()
println("sub is active!")
// Start the reader gorotuine associated with this WS.
go func(conn *websocket.Conn) {
defer sub.Close()
for {
_, p, err := conn.ReadMessage()
if err != nil {
log.Println(err)
return
}
if len(p) == 0 {
continue
}
ch := string(p[1:])
switch p[0] {
case '*':
promise, _ := sub.WaitForNewPromise(ch, 5*time.Second)
println("OK")
go func(p *mpx.Promise, ch string) {
if ch == "killme" {
p.Cancel()
}
for {
msg, ok := <-p.C
if ok {
fmt.Printf("[promise %v] Received [%v]\n", ch, string(msg))
} else {
fmt.Printf("[promise %v] Channel closed\n", ch)
break
}
}
}(promise, ch)
case '+':
promise, err := sub.NewPromise(ch, 5*time.Second)
println("OK")
if err != nil {
println("failed to create the promise: we are disconnected")
continue
}
go func(p *mpx.Promise, ch string) {
if ch == "killme" {
p.Cancel()
}
for {
msg, ok := <-p.C
if ok {
fmt.Printf("[promise %v] Received [%v]\n", ch, string(msg))
} else {
fmt.Printf("[promise %v] Channel closed\n", ch)
break
}
}
}(promise, ch)
default:
continue
}
}
}(conn)
})
err := http.ListenAndServe("127.0.0.1:7778", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}