[](https://t.me/joinchat/ABFVWBE0AhkyyhREoaboXQ) [](https://github.com/centrifugal/centrifuge/actions) [](https://codecov.io/github/centrifugal/centrifuge?branch=master) [](https://pkg.go.dev/github.com/centrifugal/centrifuge) **This library has no v1 release yet, API still evolves. Use with strict versioning.** At this moment patch version updates only have backwards compatible changes and fixes, minor version updates can have backwards-incompatible API changes. See [v1.0.0 milestone](https://github.com/centrifugal/centrifuge/milestone/1). Master branch can have unreleased code. Centrifuge library is a real-time core of [Centrifugo](https://github.com/centrifugal/centrifugo) server. It's also supposed to be a general purpose real-time messaging library for Go programming language. The library built on top of strict client-server protocol schema and exposes various real-time oriented primitives for a developer. Centrifuge solves several problems a developer may come across when building complex real-time applications – like scalability (millions of connections), proper persistent connection management and invalidation, fast reconnect with message recovery, WebSocket fallback option. Library highlights: * Fast and optimized for low-latency communication with millions of client connections. See [test stand with 1 million connections in Kubernetes](https://centrifugal.github.io/centrifugo/misc/benchmark/) * WebSocket with JSON or binary Protobuf protocol * SockJS polyfill library support for browsers where WebSocket not available (JSON only) * Built-in horizontal scalability with Redis PUB/SUB, consistent Redis sharding, Sentinel and Redis Cluster for HA * Possibility to register custom PUB/SUB broker and presence storage implementations * Native authentication over HTTP middleware or custom token-based * Bidirectional asynchronous message communication and RPC calls * Channel concept to broadcast message to all active subscribers * Client-side and server-side channel subscriptions * Presence information for channels (show all active clients in channel) * History information for channels (stream of messages published into channel) * Join/leave events for channels (aka client goes online/offline) * Message recovery mechanism for channels to survive PUB/SUB delivery problems, short network disconnects or node restart * Prometheus instrumentation * Client libraries for main application environments (see below) Client libraries: * [centrifuge-js](https://github.com/centrifugal/centrifuge-js) – for a browser, NodeJS and React Native * [centrifuge-go](https://github.com/centrifugal/centrifuge-go) - for Go language * [centrifuge-mobile](https://github.com/centrifugal/centrifuge-mobile) - for iOS/Android with `centrifuge-go` as basis and [gomobile](https://github.com/golang/mobile) * [centrifuge-dart](https://github.com/centrifugal/centrifuge-dart) - for Dart and Flutter * [centrifuge-swift](https://github.com/centrifugal/centrifuge-swift) – for native iOS development * [centrifuge-java](https://github.com/centrifugal/centrifuge-java) – for native Android development and general Java ### Explore Centrifuge * see Centrifuge [Documentation on pkg.go.dev](https://pkg.go.dev/github.com/centrifugal/centrifuge) * check out [examples](https://github.com/centrifugal/centrifuge/tree/master/_examples) folder * read [Centrifuge introduction post](https://centrifugal.github.io/centrifugo/blog/intro_centrifuge/) in Centrifugo blog * you can also consider [Centrifugo server documentation](https://centrifugal.github.io/centrifugo/) as extra doc for this package (since Centrifugo is built on top of Centrifuge library) * read this README to the end for [installation](#installation) details, [quick example](#quick-example) and [Tips and tricks](#tips-and-tricks) section ### Installation To install use: ```bash go get github.com/centrifugal/centrifuge ``` `go mod` is a recommended way of adding this library to your project dependencies. ### Quick example Let's take a look on how to build the simplest real-time chat ever with Centrifuge library. Clients will be able to connect to server over Websocket, send a message into channel and this message will be instantly delivered to all active channel subscribers. On server side we will accept all connections and will work as simple PUB/SUB proxy without worrying too much about permissions. In this example we will use Centrifuge Javascript client on a frontend. Create file `main.go` with the following code: ```go package main import ( "log" "net/http" // Import this library. "github.com/centrifugal/centrifuge" ) // Authentication middleware example. Centrifuge expects Credentials // with current user ID set. Without provided Credentials client // connection won't be accepted. Another way to authenticate connection // is reacting to node.OnConnecting event where you may authenticate // connection based on a custom token sent by a client in first protocol // frame. See _examples folder in repo to find real-life auth samples // (OAuth2, Gin sessions, JWT etc). func auth(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() // Put authentication Credentials into request Context. // Since we don't have any session backend here we simply // set user ID as empty string. Users with empty ID called // anonymous users, in real app you should decide whether // anonymous users allowed to connect to your server or not. cred := ¢rifuge.Credentials{ UserID: "", } newCtx := centrifuge.SetCredentials(ctx, cred) r = r.WithContext(newCtx) h.ServeHTTP(w, r) }) } func main() { // We use default config here as a starting point. Default config // contains reasonable values for available options. cfg := centrifuge.DefaultConfig // Node is the core object in Centrifuge library responsible for // many useful things. For example Node allows to publish messages // to channels with its Publish method. node, err := centrifuge.New(cfg) if err != nil { log.Fatal(err) } // Set ConnectHandler called when client successfully connected to Node. // Your code inside a handler must be synchronized since it will be called // concurrently from different goroutines (belonging to different client // connections). See information about connection life cycle in library readme. // This handler should not block – so do minimal work here, set required // connection event handlers and return. node.OnConnect(func(client *centrifuge.Client) { // In our example transport will always be Websocket but it can also be SockJS. transportName := client.Transport().Name() // In our example clients connect with JSON protocol but it can also be Protobuf. transportProto := client.Transport().Protocol() log.Printf("client connected via %s (%s)", transportName, transportProto) // Set SubscribeHandler to react on every channel subscription attempt // initiated by a client. Here you can theoretically return an error or // disconnect a client from a server if needed. But here we just accept // all subscriptions to all channels. In real life you may use a more // complex permission check here. The reason why we use callback style // inside client event handlers is that it gives a possibility to control // operation concurrency to developer and still control order of events. client.OnSubscribe(func(e centrifuge.SubscribeEvent, cb centrifuge.SubscribeCallback) { log.Printf("client subscribes on channel %s", e.Channel) cb(centrifuge.SubscribeReply{}, nil) }) // By default, clients can not publish messages into channels. By setting // PublishHandler we tell Centrifuge that publish from a client-side is // possible. Now each time client calls publish method this handler will be // called and you have a possibility to validate publication request. After // returning from this handler Publication will be published to a channel and // reach active subscribers with at most once delivery guarantee. In our simple // chat app we allow everyone to publish into any channel but in real case // you may have more validation. client.OnPublish(func(e centrifuge.PublishEvent, cb centrifuge.PublishCallback) { log.Printf("client publishes into channel %s: %s", e.Channel, string(e.Data)) cb(centrifuge.PublishReply{}, nil) }) // Set Disconnect handler to react on client disconnect events. client.OnDisconnect(func(e centrifuge.DisconnectEvent) { log.Printf("client disconnected") }) }) // Run node. This method does not block. See also node.Shutdown method // to finish application gracefully. if err := node.Run(); err != nil { log.Fatal(err) } // Now configure HTTP routes. // Serve Websocket connections using WebsocketHandler. wsHandler := centrifuge.NewWebsocketHandler(node, centrifuge.WebsocketConfig{}) http.Handle("/connection/websocket", auth(wsHandler)) // The second route is for serving index.html file. http.Handle("/", http.FileServer(http.Dir("./"))) log.Printf("Starting server, visit http://localhost:8000") if err := http.ListenAndServe(":8000", nil); err != nil { log.Fatal(err) } } ``` Also create file `index.html` near `main.go` with content: ```html