| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"flag" |
| 6 |
"log" |
| 7 |
"net/http" |
| 8 |
"os" |
| 9 |
"os/signal" |
| 10 |
"strconv" |
| 11 |
"syscall" |
| 12 |
"time" |
| 13 |
|
| 14 |
_ "net/http/pprof" |
| 15 |
|
| 16 |
"github.com/centrifugal/centrifuge" |
| 17 |
) |
| 18 |
|
| 19 |
var ( |
| 20 |
port = flag.Int("port", 8000, "Port to bind app to") |
| 21 |
) |
| 22 |
|
| 23 |
func handleLog(e centrifuge.LogEntry) { |
| 24 |
log.Printf("[centrifuge] %s: %v", e.Message, e.Fields) |
| 25 |
} |
| 26 |
|
| 27 |
func authMiddleware(h http.Handler) http.Handler { |
| 28 |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 29 |
ctx := r.Context() |
| 30 |
ctx = centrifuge.SetCredentials(ctx, ¢rifuge.Credentials{ |
| 31 |
UserID: "42", |
| 32 |
Info: []byte(`{"name": "Alexander"}`), |
| 33 |
}) |
| 34 |
r = r.WithContext(ctx) |
| 35 |
h.ServeHTTP(w, r) |
| 36 |
}) |
| 37 |
} |
| 38 |
|
| 39 |
func waitExitSignal(n *centrifuge.Node) { |
| 40 |
sigCh := make(chan os.Signal, 1) |
| 41 |
done := make(chan bool, 1) |
| 42 |
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM) |
| 43 |
go func() { |
| 44 |
<-sigCh |
| 45 |
_ = n.Shutdown(context.Background()) |
| 46 |
done <- true |
| 47 |
}() |
| 48 |
<-done |
| 49 |
} |
| 50 |
|
| 51 |
func main() { |
| 52 |
flag.Parse() |
| 53 |
|
| 54 |
cfg := centrifuge.DefaultConfig |
| 55 |
cfg.LogLevel = centrifuge.LogLevelDebug |
| 56 |
cfg.LogHandler = handleLog |
| 57 |
|
| 58 |
node, _ := centrifuge.New(cfg) |
| 59 |
|
| 60 |
node.OnConnect(func(client *centrifuge.Client) { |
| 61 |
transport := client.Transport() |
| 62 |
log.Printf("user %s connected via %s with protocol: %s", client.UserID(), transport.Name(), transport.Protocol()) |
| 63 |
|
| 64 |
client.OnSubscribe(func(e centrifuge.SubscribeEvent, cb centrifuge.SubscribeCallback) { |
| 65 |
log.Printf("user %s subscribes on %s", client.UserID(), e.Channel) |
| 66 |
cb(centrifuge.SubscribeReply{ |
| 67 |
Options: centrifuge.SubscribeOptions{ |
| 68 |
Presence: true, |
| 69 |
JoinLeave: true, |
| 70 |
Recover: true, |
| 71 |
}, |
| 72 |
}, nil) |
| 73 |
}) |
| 74 |
|
| 75 |
client.OnUnsubscribe(func(e centrifuge.UnsubscribeEvent) { |
| 76 |
log.Printf("user %s unsubscribed from %s", client.UserID(), e.Channel) |
| 77 |
}) |
| 78 |
|
| 79 |
client.OnPublish(func(e centrifuge.PublishEvent, cb centrifuge.PublishCallback) { |
| 80 |
log.Printf("user %s publishes into channel %s: %s", client.UserID(), e.Channel, string(e.Data)) |
| 81 |
cb(centrifuge.PublishReply{ |
| 82 |
Options: centrifuge.PublishOptions{ |
| 83 |
HistorySize: 100, |
| 84 |
HistoryTTL: 5 * time.Second, |
| 85 |
}, |
| 86 |
}, nil) |
| 87 |
}) |
| 88 |
|
| 89 |
client.OnPresence(func(e centrifuge.PresenceEvent, cb centrifuge.PresenceCallback) { |
| 90 |
cb(centrifuge.PresenceReply{}, nil) |
| 91 |
}) |
| 92 |
|
| 93 |
client.OnDisconnect(func(e centrifuge.DisconnectEvent) { |
| 94 |
log.Printf("user %s disconnected, disconnect: %s", client.UserID(), e.Disconnect) |
| 95 |
}) |
| 96 |
}) |
| 97 |
|
| 98 |
redisShardConfigs := []centrifuge.RedisShardConfig{ |
| 99 |
{Address: "localhost:6379"}, |
| 100 |
{Address: "localhost:6380"}, |
| 101 |
} |
| 102 |
var redisShards []*centrifuge.RedisShard |
| 103 |
for _, redisConf := range redisShardConfigs { |
| 104 |
redisShard, err := centrifuge.NewRedisShard(node, redisConf) |
| 105 |
if err != nil { |
| 106 |
log.Fatal(err) |
| 107 |
} |
| 108 |
redisShards = append(redisShards, redisShard) |
| 109 |
} |
| 110 |
|
| 111 |
broker, err := centrifuge.NewRedisBroker(node, centrifuge.RedisBrokerConfig{ |
| 112 |
// We are using Redis streams here for history. |
| 113 |
UseStreams: true, |
| 114 |
|
| 115 |
// Use reasonably large expiration interval for stream meta key, |
| 116 |
// much bigger than maximum HistoryLifetime value in Node config. |
| 117 |
// This way stream meta data will expire, in some cases you may want |
| 118 |
// to prevent its expiration setting this to zero value. |
| 119 |
HistoryMetaTTL: 7 * 24 * time.Hour, |
| 120 |
|
| 121 |
// And configure a couple of shards to use. |
| 122 |
Shards: redisShards, |
| 123 |
}) |
| 124 |
if err != nil { |
| 125 |
log.Fatal(err) |
| 126 |
} |
| 127 |
node.SetBroker(broker) |
| 128 |
|
| 129 |
presenceManager, err := centrifuge.NewRedisPresenceManager(node, centrifuge.RedisPresenceManagerConfig{ |
| 130 |
Shards: redisShards, |
| 131 |
}) |
| 132 |
if err != nil { |
| 133 |
log.Fatal(err) |
| 134 |
} |
| 135 |
node.SetPresenceManager(presenceManager) |
| 136 |
|
| 137 |
if err := node.Run(); err != nil { |
| 138 |
log.Fatal(err) |
| 139 |
} |
| 140 |
|
| 141 |
go func() { |
| 142 |
// Publish channel notifications from server periodically. |
| 143 |
i := 1 |
| 144 |
for { |
| 145 |
_, err := node.Publish("chat:index", []byte(`{"input": "`+strconv.Itoa(i)+`"}`)) |
| 146 |
if err != nil { |
| 147 |
log.Printf("error publishing to personal channel: %s", err) |
| 148 |
} |
| 149 |
i++ |
| 150 |
time.Sleep(5000 * time.Millisecond) |
| 151 |
} |
| 152 |
}() |
| 153 |
|
| 154 |
// Simulate some work inside Redis. |
| 155 |
for i := 0; i < 10; i++ { |
| 156 |
go func(i int) { |
| 157 |
for { |
| 158 |
time.Sleep(time.Second) |
| 159 |
_, err := node.Publish("chat:"+strconv.Itoa(i), []byte("hello")) |
| 160 |
if err != nil { |
| 161 |
log.Println(err.Error()) |
| 162 |
} |
| 163 |
_, err = node.History("chat:" + strconv.Itoa(i)) |
| 164 |
if err != nil { |
| 165 |
log.Println(err.Error()) |
| 166 |
} |
| 167 |
} |
| 168 |
}(i) |
| 169 |
} |
| 170 |
|
| 171 |
http.Handle("/connection/websocket", authMiddleware(centrifuge.NewWebsocketHandler(node, centrifuge.WebsocketConfig{}))) |
| 172 |
http.Handle("/", http.FileServer(http.Dir("./"))) |
| 173 |
|
| 174 |
go func() { |
| 175 |
if err := http.ListenAndServe(":"+strconv.Itoa(*port), nil); err != nil { |
| 176 |
log.Fatal(err) |
| 177 |
} |
| 178 |
}() |
| 179 |
|
| 180 |
waitExitSignal(node) |
| 181 |
log.Println("bye!") |
| 182 |
} |