-
Notifications
You must be signed in to change notification settings - Fork 49
/
main.go
69 lines (60 loc) · 1.54 KB
/
main.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
package main
import (
"net/http"
"os"
"time"
"github.com/heroku/x/hredis/redigo"
"github.com/sirupsen/logrus"
)
var (
waitTimeout = time.Minute * 10
log = logrus.WithField("cmd", "go-websocket-chat-demo")
rr redisReceiver
rw redisWriter
)
func main() {
port := os.Getenv("PORT")
if port == "" {
log.WithField("PORT", port).Fatal("$PORT must be set")
}
redisURL := os.Getenv("REDIS_URL")
if redisURL == "" {
log.WithField("REDIS_URL", redisURL).Fatal("$REDIS_URL must be set")
}
redisPool, err := redigo.NewRedisPoolFromURL(redisURL)
if err != nil {
log.WithField("url", redisURL).Fatal("Unable to create Redis pool")
}
rr = newRedisReceiver(redisPool)
rw = newRedisWriter(redisPool)
go func() {
for {
waited, err := redigo.WaitForAvailability(redisURL, waitTimeout, rr.wait)
if !waited || err != nil {
log.WithFields(logrus.Fields{"waitTimeout": waitTimeout, "err": err}).Fatal("Redis not available by timeout!")
}
rr.broadcast(availableMessage)
err = rr.run()
if err == nil {
break
}
log.Error(err)
}
}()
go func() {
for {
waited, err := redigo.WaitForAvailability(redisURL, waitTimeout, nil)
if !waited || err != nil {
log.WithFields(logrus.Fields{"waitTimeout": waitTimeout, "err": err}).Fatal("Redis not available by timeout!")
}
err = rw.run()
if err == nil {
break
}
log.Error(err)
}
}()
http.Handle("/", http.FileServer(http.Dir("./public")))
http.HandleFunc("/ws", handleWebsocket)
log.Println(http.ListenAndServe(":"+port, nil))
}