| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"encoding/json" |
| 6 |
"io" |
| 7 |
"log" |
| 8 |
"net/http" |
| 9 |
"os" |
| 10 |
"os/signal" |
| 11 |
"strconv" |
| 12 |
"syscall" |
| 13 |
"time" |
| 14 |
|
| 15 |
_ "net/http/pprof" |
| 16 |
|
| 17 |
"github.com/centrifugal/centrifuge" |
| 18 |
"github.com/prometheus/client_golang/prometheus/promhttp" |
| 19 |
) |
| 20 |
|
| 21 |
type clientMessage struct { |
| 22 |
Timestamp int64 `json:"timestamp"` |
| 23 |
Input string `json:"input"` |
| 24 |
} |
| 25 |
|
| 26 |
func handleLog(e centrifuge.LogEntry) { |
| 27 |
log.Printf("%s: %v", e.Message, e.Fields) |
| 28 |
} |
| 29 |
|
| 30 |
func authMiddleware(h http.Handler) http.Handler { |
| 31 |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 32 |
ctx := r.Context() |
| 33 |
newCtx := centrifuge.SetCredentials(ctx, ¢rifuge.Credentials{ |
| 34 |
UserID: "42", |
| 35 |
ExpireAt: time.Now().Unix() + 60, |
| 36 |
Info: []byte(`{"name": "Alexander"}`), |
| 37 |
}) |
| 38 |
r = r.WithContext(newCtx) |
| 39 |
h.ServeHTTP(w, r) |
| 40 |
}) |
| 41 |
} |
| 42 |
|
| 43 |
func waitExitSignal(n *centrifuge.Node) { |
| 44 |
sigCh := make(chan os.Signal, 1) |
| 45 |
done := make(chan bool, 1) |
| 46 |
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM) |
| 47 |
go func() { |
| 48 |
<-sigCh |
| 49 |
_ = n.Shutdown(context.Background()) |
| 50 |
done <- true |
| 51 |
}() |
| 52 |
<-done |
| 53 |
} |
| 54 |
|
| 55 |
const exampleChannel = "chat:index" |
| 56 |
|
| 57 |
// Check whether channel is allowed for subscribing. In real case permission |
| 58 |
// check will probably be more complex than in this example. |
| 59 |
func channelSubscribeAllowed(channel string) bool { |
| 60 |
return channel == exampleChannel |
| 61 |
} |
| 62 |
|
| 63 |
func main() { |
| 64 |
cfg := centrifuge.DefaultConfig |
| 65 |
|
| 66 |
cfg.LogLevel = centrifuge.LogLevelInfo |
| 67 |
cfg.LogHandler = handleLog |
| 68 |
|
| 69 |
node, _ := centrifuge.New(cfg) |
| 70 |
|
| 71 |
// Override default broker which does not use HistoryMetaTTL. |
| 72 |
broker, _ := centrifuge.NewMemoryBroker(node, centrifuge.MemoryBrokerConfig{ |
| 73 |
HistoryMetaTTL: 120 * time.Second, |
| 74 |
}) |
| 75 |
node.SetBroker(broker) |
| 76 |
|
| 77 |
node.OnConnecting(func(ctx context.Context, e centrifuge.ConnectEvent) (centrifuge.ConnectReply, error) { |
| 78 |
cred, _ := centrifuge.GetCredentials(ctx) |
| 79 |
return centrifuge.ConnectReply{ |
| 80 |
Data: []byte(`{}`), |
| 81 |
// Subscribe to personal several server-side channel. |
| 82 |
Subscriptions: map[string]centrifuge.SubscribeOptions{ |
| 83 |
"#" + cred.UserID: {Recover: true, Presence: true, JoinLeave: true}, |
| 84 |
}, |
| 85 |
}, nil |
| 86 |
}) |
| 87 |
|
| 88 |
node.OnConnect(func(client *centrifuge.Client) { |
| 89 |
transport := client.Transport() |
| 90 |
log.Printf("user %s connected via %s with protocol: %s", client.UserID(), transport.Name(), transport.Protocol()) |
| 91 |
|
| 92 |
// Event handler should not block, so start separate goroutine to |
| 93 |
// periodically send messages to client. |
| 94 |
go func() { |
| 95 |
for { |
| 96 |
select { |
| 97 |
case <-client.Context().Done(): |
| 98 |
return |
| 99 |
case <-time.After(5 * time.Second): |
| 100 |
err := client.Send([]byte(`{"time": "` + strconv.FormatInt(time.Now().Unix(), 10) + `"}`)) |
| 101 |
if err != nil { |
| 102 |
if err == io.EOF { |
| 103 |
return |
| 104 |
} |
| 105 |
log.Printf("error sending message: %s", err) |
| 106 |
} |
| 107 |
} |
| 108 |
} |
| 109 |
}() |
| 110 |
|
| 111 |
client.OnAlive(func() { |
| 112 |
log.Printf("user %s connection is still active", client.UserID()) |
| 113 |
}) |
| 114 |
|
| 115 |
client.OnRefresh(func(e centrifuge.RefreshEvent, cb centrifuge.RefreshCallback) { |
| 116 |
log.Printf("user %s connection is going to expire, refreshing", client.UserID()) |
| 117 |
cb(centrifuge.RefreshReply{ |
| 118 |
ExpireAt: time.Now().Unix() + 60, |
| 119 |
}, nil) |
| 120 |
}) |
| 121 |
|
| 122 |
client.OnSubscribe(func(e centrifuge.SubscribeEvent, cb centrifuge.SubscribeCallback) { |
| 123 |
log.Printf("user %s subscribes on %s", client.UserID(), e.Channel) |
| 124 |
if !channelSubscribeAllowed(e.Channel) { |
| 125 |
cb(centrifuge.SubscribeReply{}, centrifuge.ErrorPermissionDenied) |
| 126 |
return |
| 127 |
} |
| 128 |
cb(centrifuge.SubscribeReply{ |
| 129 |
Options: centrifuge.SubscribeOptions{ |
| 130 |
Recover: true, |
| 131 |
Presence: true, |
| 132 |
JoinLeave: true, |
| 133 |
}, |
| 134 |
}, nil) |
| 135 |
}) |
| 136 |
|
| 137 |
client.OnUnsubscribe(func(e centrifuge.UnsubscribeEvent) { |
| 138 |
log.Printf("user %s unsubscribed from %s", client.UserID(), e.Channel) |
| 139 |
}) |
| 140 |
|
| 141 |
client.OnPublish(func(e centrifuge.PublishEvent, cb centrifuge.PublishCallback) { |
| 142 |
log.Printf("user %s publishes into channel %s: %s", client.UserID(), e.Channel, string(e.Data)) |
| 143 |
if !client.IsSubscribed(e.Channel) { |
| 144 |
cb(centrifuge.PublishReply{}, centrifuge.ErrorPermissionDenied) |
| 145 |
return |
| 146 |
} |
| 147 |
|
| 148 |
var msg clientMessage |
| 149 |
err := json.Unmarshal(e.Data, &msg) |
| 150 |
if err != nil { |
| 151 |
cb(centrifuge.PublishReply{}, centrifuge.ErrorBadRequest) |
| 152 |
return |
| 153 |
} |
| 154 |
msg.Timestamp = time.Now().Unix() |
| 155 |
data, _ := json.Marshal(msg) |
| 156 |
|
| 157 |
result, err := node.Publish( |
| 158 |
e.Channel, data, |
| 159 |
centrifuge.WithHistory(300, time.Minute), |
| 160 |
centrifuge.WithClientInfo(e.ClientInfo), |
| 161 |
) |
| 162 |
|
| 163 |
cb(centrifuge.PublishReply{Result: &result}, err) |
| 164 |
}) |
| 165 |
|
| 166 |
client.OnRPC(func(e centrifuge.RPCEvent, cb centrifuge.RPCCallback) { |
| 167 |
log.Printf("RPC from user: %s, data: %s, method: %s", client.UserID(), string(e.Data), e.Method) |
| 168 |
cb(centrifuge.RPCReply{ |
| 169 |
Data: []byte(`{"year": "2020"}`), |
| 170 |
}, nil) |
| 171 |
}) |
| 172 |
|
| 173 |
client.OnPresence(func(e centrifuge.PresenceEvent, cb centrifuge.PresenceCallback) { |
| 174 |
log.Printf("user %s calls presence on %s", client.UserID(), e.Channel) |
| 175 |
if !client.IsSubscribed(e.Channel) { |
| 176 |
cb(centrifuge.PresenceReply{}, centrifuge.ErrorPermissionDenied) |
| 177 |
return |
| 178 |
} |
| 179 |
cb(centrifuge.PresenceReply{}, nil) |
| 180 |
}) |
| 181 |
|
| 182 |
client.OnMessage(func(e centrifuge.MessageEvent) { |
| 183 |
log.Printf("message from user: %s, data: %s", client.UserID(), string(e.Data)) |
| 184 |
}) |
| 185 |
|
| 186 |
client.OnDisconnect(func(e centrifuge.DisconnectEvent) { |
| 187 |
log.Printf("user %s disconnected, disconnect: %s", client.UserID(), e.Disconnect) |
| 188 |
}) |
| 189 |
}) |
| 190 |
|
| 191 |
if err := node.Run(); err != nil { |
| 192 |
log.Fatal(err) |
| 193 |
} |
| 194 |
|
| 195 |
go func() { |
| 196 |
// Publish personal notifications for user 42 periodically. |
| 197 |
i := 1 |
| 198 |
for { |
| 199 |
_, err := node.Publish("#42", []byte(`{"personal": "`+strconv.Itoa(i)+`"}`), centrifuge.WithHistory(300, time.Minute)) |
| 200 |
if err != nil { |
| 201 |
log.Printf("error publishing to personal channel: %s", err) |
| 202 |
} |
| 203 |
i++ |
| 204 |
time.Sleep(5000 * time.Millisecond) |
| 205 |
} |
| 206 |
}() |
| 207 |
|
| 208 |
go func() { |
| 209 |
// Publish to channel periodically. |
| 210 |
i := 1 |
| 211 |
for { |
| 212 |
_, err := node.Publish("chat:index", []byte(`{"input": "Publish from server `+strconv.Itoa(i)+`"}`), centrifuge.WithHistory(300, time.Minute)) |
| 213 |
if err != nil { |
| 214 |
log.Printf("error publishing to personal channel: %s", err) |
| 215 |
} |
| 216 |
i++ |
| 217 |
time.Sleep(10000 * time.Millisecond) |
| 218 |
} |
| 219 |
}() |
| 220 |
|
| 221 |
websocketHandler := centrifuge.NewWebsocketHandler(node, centrifuge.WebsocketConfig{ |
| 222 |
ReadBufferSize: 1024, |
| 223 |
UseWriteBufferPool: true, |
| 224 |
}) |
| 225 |
http.Handle("/connection/websocket", authMiddleware(websocketHandler)) |
| 226 |
|
| 227 |
sockjsHandler := centrifuge.NewSockjsHandler(node, centrifuge.SockjsConfig{ |
| 228 |
URL: "https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js", |
| 229 |
HandlerPrefix: "/connection/sockjs", |
| 230 |
WebsocketReadBufferSize: 1024, |
| 231 |
WebsocketWriteBufferSize: 1024, |
| 232 |
}) |
| 233 |
http.Handle("/connection/sockjs/", authMiddleware(sockjsHandler)) |
| 234 |
|
| 235 |
http.Handle("/metrics", promhttp.Handler()) |
| 236 |
http.Handle("/", http.FileServer(http.Dir("./"))) |
| 237 |
|
| 238 |
go func() { |
| 239 |
if err := http.ListenAndServe(":8000", nil); err != nil { |
| 240 |
log.Fatal(err) |
| 241 |
} |
| 242 |
}() |
| 243 |
|
| 244 |
waitExitSignal(node) |
| 245 |
log.Println("bye!") |
| 246 |
} |