Skip to content

Instantly share code, notes, and snippets.

@FZambia
Created June 20, 2020 18:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FZambia/2c2d3589b3076d1db59fdc3a60e75914 to your computer and use it in GitHub Desktop.
Save FZambia/2c2d3589b3076d1db59fdc3a60e75914 to your computer and use it in GitHub Desktop.
Centrifuge introduction example source code
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="https://rawgit.com/centrifugal/centrifuge-js/master/dist/centrifuge.min.js"></script>
</head>
<body>
<script type="text/javascript">
const centrifuge = new Centrifuge('ws://localhost:8000/websocket');
function drawText(text) {
const div = document.createElement('div');
div.innerHTML = text + '<br>';
document.body.appendChild(div);
}
centrifuge.on('connect', function(ctx){
drawText('Connected over ' + ctx.transport);
});
centrifuge.on('disconnect', function(ctx){
drawText('Disconnected: ' + ctx.reason);
});
centrifuge.subscribe("chat", function(ctx) {
drawText(JSON.stringify(ctx.data.text));
});
// After setting event handlers – initiate actual connection with server.
centrifuge.connect();
</script>
</body>
</html>
package main
import (
"context"
"log"
"net/http"
"time"
// Import this library.
"github.com/centrifugal/centrifuge"
)
func handleLog(e centrifuge.LogEntry) {
log.Printf("%s: %v", e.Message, e.Fields)
}
func authMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
newCtx := centrifuge.SetCredentials(ctx, &centrifuge.Credentials{
UserID: "",
})
r = r.WithContext(newCtx)
h.ServeHTTP(w, r)
})
}
func main() {
// We use default config here as starting point.
// Default config contains reasonable values for available options.
cfg := centrifuge.DefaultConfig
// Centrifuge library exposes logs with different log level. In your app
// you can set special function to handle these log entries in a way you want.
cfg.LogLevel = centrifuge.LogLevelDebug
cfg.LogHandler = handleLog
cfg.Anonymous = true
// Node is the core object in Centrifuge library responsible for many
// useful things. Here we initialize new Node instance and pass config
// to it.
node, _ := centrifuge.New(cfg)
// ClientConnected node event handler is a point where you generally
// create a binding between Centrifuge and your app business logic.
// Callback function you pass here will be called every time new
// connection established with server. Inside this callback function
// you can set various event handlers for connection.
node.On().ClientConnected(func(ctx context.Context, client *centrifuge.Client) {
// Set Subscribe Handler to react on every channel subscription
// attempt initiated by client. Here you can theoretically return
// an error or disconnect client from server if needed. But now
// we just accept all subscriptions.
client.On().Subscribe(func(e centrifuge.SubscribeEvent) centrifuge.SubscribeReply {
log.Printf("client subscribes on channel %s", e.Channel)
return centrifuge.SubscribeReply{}
})
// Set Disconnect handler to react on client disconnect events.
client.On().Disconnect(func(e centrifuge.DisconnectEvent) centrifuge.DisconnectReply {
log.Printf("client disconnected")
return centrifuge.DisconnectReply{}
})
log.Println("client connected")
})
// Run node.
_ = node.Run()
go func() {
for range time.NewTicker(5 * time.Second).C {
_, _ = node.Publish("chat", []byte(`{"text": "hello from server"}`))
}
}()
wsHandler := centrifuge.NewWebsocketHandler(node, centrifuge.WebsocketConfig{})
http.Handle("/websocket", authMiddleware(wsHandler))
http.Handle("/", http.FileServer(http.Dir("./")))
if err := http.ListenAndServe(":8000", nil); err != nil {
log.Println(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment