### Get active channels with Go (gocent) Source: https://context7.com/centrifugal/gocent/llms.txt Demonstrates retrieving active channels (with subscribers) from Centrifugal server, including pattern matching. Requires gocent v3 client library and valid API credentials. ```go package main import ( "context" "log" "github.com/centrifugal/gocent/v3" ) func main() { client := gocent.New(gocent.Config{ Addr: "http://localhost:8000/api", Key: "your-api-key-here", }) ctx := context.Background() // Get all active channels result, err := client.Channels(ctx) if err != nil { log.Fatalf("Channels failed: %v", err) } log.Printf("Total active channels: %d", len(result.Channels)) for channel, info := range result.Channels { log.Printf(" %s: %d users", channel, info.NumUsers) } // Get channels matching a pattern result, err = client.Channels(ctx, gocent.WithPattern("chat:*")) if err != nil { log.Fatalf("Channels failed: %v", err) } log.Printf("Active chat channels: %d", len(result.Channels)) for channel, info := range result.Channels { log.Printf(" %s: %d users", channel, info.NumUsers) } // Get channels matching another pattern result, err = client.Channels(ctx, gocent.WithPattern("notifications:*")) if err != nil { log.Fatalf("Channels failed: %v", err) } log.Printf("Active notification channels: %d", len(result.Channels)) } ``` -------------------------------- ### Get Channel Presence Stats with gocent Source: https://context7.com/centrifugal/gocent/llms.txt Retrieves condensed presence statistics for a channel, providing only counters for unique users and total connections. This is more efficient than fetching full presence details. ```go package main import ( "context" "log" "github.com/centrifugal/gocent/v3" ) func main() { client := gocent.New(gocent.Config{ Addr: "http://localhost:8000/api", Key: "your-api-key-here", }) ctx := context.Background() channel := "chat:lobby" // Get presence stats (more efficient than full presence) result, err := client.PresenceStats(ctx, channel) if err != nil { log.Fatalf("PresenceStats failed: %v", err) } log.Printf("Channel %s statistics:", channel) log.Printf(" Unique users: %d", result.NumUsers) log.Printf(" Total connections: %d", result.NumClients) log.Printf(" Avg connections per user: %.2f", float64(result.NumClients)/float64(result.NumUsers)) } ``` -------------------------------- ### Get Centrifugo Server Cluster Info using Go Source: https://context7.com/centrifugal/gocent/llms.txt Retrieves and logs detailed information about all nodes in a Centrifugo cluster, including their status, version, uptime, and connection statistics. Requires the gocent library and a valid API key. ```go package main import ( "context" "log" "github.com/centrifugal/gocent/v3" ) func main() { client := gocent.New(gocent.Config{ Addr: "http://localhost:8000/api", Key: "your-api-key-here", }) ctx := context.Background() // Get cluster information result, err := client.Info(ctx) if err != nil { log.Fatalf("Info failed: %v", err) } log.Printf("Centrifugo cluster status:") log.Printf(" Total nodes: %d", len(result.Nodes)) var totalClients, totalUsers, totalChannels int for _, node := range result.Nodes { log.Printf("\nNode: %s", node.Name) log.Printf(" UID: %s", node.UID) log.Printf(" Version: %s", node.Version) log.Printf(" Uptime: %d seconds", node.Uptime) log.Printf(" Clients: %d", node.NumClients) log.Printf(" Users: %d", node.NumUsers) log.Printf(" Channels: %d", node.NumChannels) totalClients += node.NumClients totalUsers += node.NumUsers totalChannels += node.NumChannels } log.Printf("\nCluster totals:") log.Printf(" Total clients: %d", totalClients) log.Printf(" Total users: %d", totalUsers) log.Printf(" Total channels: %d", totalChannels) } ``` -------------------------------- ### Get Channel Presence Information with gocent Source: https://context7.com/centrifugal/gocent/llms.txt Retrieves detailed presence information for all clients subscribed to a specific channel. It iterates through connected clients, logs their details, and counts unique users. ```go package main import ( "context" "log" "github.com/centrifugal/gocent/v3" ) func main() { client := gocent.New(gocent.Config{ Addr: "http://localhost:8000/api", Key: "your-api-key-here", }) ctx := context.Background() channel := "chat:lobby" // Get full presence information result, err := client.Presence(ctx, channel) if err != nil { log.Fatalf("Presence failed: %v", err) } log.Printf("Channel %s has %d connections", channel, len(result.Presence)) // Iterate through all connected clients for clientID, clientInfo := range result.Presence { log.Printf("Client %s: User=%s, ConnInfo=%s, ChanInfo=%s", clientID, clientInfo.User, string(clientInfo.ConnInfo), string(clientInfo.ChanInfo)) } // Count unique users uniqueUsers := make(map[string]bool) for _, clientInfo := range result.Presence { uniqueUsers[clientInfo.User] = true } log.Printf("Total unique users: %d", len(uniqueUsers)) } ``` -------------------------------- ### Initialize Gocent Client (Go) Source: https://context7.com/centrifugal/gocent/llms.txt Initializes a Gocent client for Centrifugo. Supports basic configuration, custom HTTP clients for advanced control (e.g., timeouts), and dynamic endpoint resolution via a GetAddr function. Demonstrates a connection test using the Info call. ```go package main import ( "context" "log" "net/http" "time" "github.com/centrifugal/gocent/v3" ) func main() { // Basic client configuration client := gocent.New(gocent.Config{ Addr: "http://localhost:8000/api", Key: "your-api-key-here", }) // Client with custom HTTP client customHTTPClient := &http.Client{ Timeout: 5 * time.Second, Transport: &http.Transport{ MaxIdleConnsPerHost: 50, }, } clientWithCustomHTTP := gocent.New(gocent.Config{ Addr: "http://localhost:8000/api", Key: "your-api-key-here", HTTPClient: customHTTPClient, }) // Client with dynamic endpoint resolution clientWithDynamicAddr := gocent.New(gocent.Config{ Key: "your-api-key-here", GetAddr: func() (string, error) { // Dynamically determine the endpoint (e.g., from service discovery) return "http://centrifugo-node1:8000/api", nil }, }) ctx := context.Background() // Test connection with Info call info, err := client.Info(ctx) if err != nil { log.Fatalf("Failed to connect: %v", err) } log.Printf("Connected to %d Centrifugo nodes", len(info.Nodes)) } ``` -------------------------------- ### Batch Execute Centrifugo Commands using Go Pipe Source: https://context7.com/centrifugal/gocent/llms.txt Demonstrates how to batch multiple Centrifugo API commands into a single HTTP request using the Pipe feature for improved performance. Supports mixed operations like publish, subscribe, presence stats, history retrieval, and info requests. Requires the gocent library. ```go package main import ( "context" "encoding/json" "log" "github.com/centrifugal/gocent/v3" ) func main() { client := gocent.New(gocent.Config{ Addr: "http://localhost:8000/api", Key: "your-api-key-here", }) ctx := context.Background() // Create a pipe for batching commands pipe := client.Pipe() // Add multiple publish commands message1, _ := json.Marshal(map[string]string{"msg": "First message"}) message2, _ := json.Marshal(map[string]string{"msg": "Second message"}) message3, _ := json.Marshal(map[string]string{"msg": "Third message"}) err := pipe.AddPublish("chat:room1", message1) if err != nil { log.Fatalf("AddPublish failed: %v", err) } err = pipe.AddPublish("chat:room2", message2) if err != nil { log.Fatalf("AddPublish failed: %v", err) } err = pipe.AddPublish("chat:room3", message3) if err != nil { log.Fatalf("AddPublish failed: %v", err) } // Send all commands in one HTTP request replies, err := client.SendPipe(ctx, pipe) if err != nil { log.Fatalf("SendPipe failed: %v", err) } // Process each reply for i, reply := range replies { if reply.Error != nil { log.Printf("Command %d failed: %v", i, reply.Error) } else { log.Printf("Command %d succeeded", i) } } // Complex pipe with mixed operations pipe2 := client.Pipe() // Publish to channel _ = pipe2.AddPublish("updates:global", []byte(`{"event": "update"}`)) // Subscribe user _ = pipe2.AddSubscribe("personal:user456", "user456", gocent.WithPresence(true)) // Get presence stats _ = pipe2.AddPresenceStats("chat:lobby") // Get history _ = pipe2.AddHistory("chat:room1", gocent.WithLimit(5)) // Get server info _ = pipe2.AddInfo() // Execute all commands replies, err = client.SendPipe(ctx, pipe2) if err != nil { log.Fatalf("SendPipe failed: %v", err) } log.Printf("Executed %d commands in one request", len(replies)) // Parse specific results if replies[0].Error == nil { var pubResult gocent.PublishResult json.Unmarshal(replies[0].Result, &pubResult) log.Printf("Publish result: offset=%d", pubResult.Offset) } if replies[2].Error == nil { var statsResult gocent.PresenceStatsResult json.Unmarshal(replies[2].Result, &statsResult) log.Printf("Presence stats: %d users, %d clients", statsResult.NumUsers, statsResult.NumClients) } // Reuse pipe by resetting pipe2.Reset() _ = pipe2.AddPublish("channel1", []byte(`{}`)) replies, err = client.SendPipe(ctx, pipe2) if err != nil { log.Fatalf("SendPipe failed: %v", err) } log.Printf("Pipe reset and reused successfully") } ``` -------------------------------- ### Go: Handle Batch Operation Errors with Gocent Pipe Source: https://context7.com/centrifugal/gocent/llms.txt This Go code snippet shows how to use the Gocent library to send multiple commands in a single batch (pipe). It demonstrates how to add commands, send the pipe, and then iterate through the replies to check for individual command errors or successful results. Dependencies include the 'context', 'encoding/json', 'log', and 'github.com/centrifugal/gocent/v3' packages. It handles network errors during pipe sending and parses individual reply results, logging successes and failures. ```go package main import ( "context" "encoding/json" "log" "github.com/centrifugal/gocent/v3" ) func main() { client := gocent.New(gocent.Config{ Addr: "http://localhost:8000/api", Key: "your-api-key-here", }) ctx := context.Background() pipe := client.Pipe() // Add commands that might fail channels := []string{"chat:room1", "chat:room2", "invalid:channel"} for _, channel := range channels { data, _ := json.Marshal(map[string]string{ "channel": channel, "message": "Test message", }) _ = pipe.AddPublish(channel, data) } // Send pipe and handle errors replies, err := client.SendPipe(ctx, pipe) if err != nil { // Network error or HTTP error log.Fatalf("SendPipe network error: %v", err) } // Check individual command results successCount := 0 failCount := 0 for i, reply := range replies { if reply.Error != nil { failCount++ log.Printf("Command %d (%s) failed: code=%d, message=%s", i, channels[i], reply.Error.Code, reply.Error.Message) } else { successCount++ var result gocent.PublishResult if err := json.Unmarshal(reply.Result, &result); err != nil { log.Printf("Failed to parse result: %v", err) } else { log.Printf("Command %d (%s) succeeded: offset=%d", i, channels[i], result.Offset) } } } log.Printf("Batch completed: %d succeeded, %d failed", successCount, failCount) } ``` -------------------------------- ### Subscribe User to Channel with Go Source: https://context7.com/centrifugal/gocent/llms.txt Subscribe a user to a channel using server-side subscriptions with configurable options. This function allows enabling presence, join/leave messages, message recovery, and custom channel information or data payloads. It requires a context, channel name, user ID, and optional configuration functions. ```go package main import ( "context" "encoding/json" "log" "github.com/centrifugal/gocent/v3" ) func main() { client := gocent.New(gocent.Config{ Addr: "http://localhost:8000/api", Key: "your-api-key-here", }) ctx := context.Background() channel := "personal:user123" userID := "user123" // Basic subscription err := client.Subscribe(ctx, channel, userID) if err != nil { log.Fatalf("Subscribe failed: %v", err) } log.Printf("User %s subscribed to %s", userID, channel) // Subscribe with presence enabled err = client.Subscribe(ctx, "chat:room1", userID, gocent.WithPresence(true)) if err != nil { log.Fatalf("Subscribe failed: %v", err) } // Subscribe with join/leave messages enabled err = client.Subscribe(ctx, "chat:room2", userID, gocent.WithPresence(true), gocent.WithJoinLeave(true)) if err != nil { log.Fatalf("Subscribe failed: %v", err) } // Subscribe with message recovery enabled err = client.Subscribe(ctx, "updates:critical", userID, gocent.WithRecover(true), gocent.WithPosition(true)) if err != nil { log.Fatalf("Subscribe failed: %v", err) } log.Printf("User subscribed with recovery enabled") // Subscribe with custom channel info channelInfo := map[string]string{"role": "moderator", "level": "5"} channelInfoJSON, _ := json.Marshal(channelInfo) err = client.Subscribe(ctx, "chat:vip", userID, gocent.WithSubscribeInfo(channelInfoJSON), gocent.WithPresence(true)) if err != nil { log.Fatalf("Subscribe failed: %v", err) } // Subscribe with custom data pushed to client welcomeData := map[string]string{"message": "Welcome to VIP room!"} welcomeDataJSON, _ := json.Marshal(welcomeData) err = client.Subscribe(ctx, "chat:vip", userID, gocent.WithSubscribeData(welcomeDataJSON)) if err != nil { log.Fatalf("Subscribe failed: %v", err) } log.Printf("User subscribed with welcome message") } ``` -------------------------------- ### Publish Messages to Centrifugo Channel (Go) Source: https://context7.com/centrifugal/gocent/llms.txt Publishes messages to a specified channel in Centrifugo. Supports basic publishing, skipping history, using idempotency keys for safe retries, and enabling delta compression with versioning. Requires a configured Gocent client. ```go package main import ( "context" "encoding/json" "log" "github.com/centrifugal/gocent/v3" ) func main() { client := gocent.New(gocent.Config{ Addr: "http://localhost:8000/api", Key: "your-api-key-here", }) ctx := context.Background() channel := "chat:room1" // Simple publish message := map[string]interface{}{ "text": "Hello, World!", "author": "user123", "time": 1234567890, } messageData, _ := json.Marshal(message) result, err := client.Publish(ctx, channel, messageData) if err != nil { log.Fatalf("Publish failed: %v", err) } log.Printf("Published to %s, offset: %d, epoch: %s", channel, result.Offset, result.Epoch) // Publish with options - skip history result, err = client.Publish(ctx, channel, messageData, gocent.WithSkipHistory(true)) if err != nil { log.Fatalf("Publish failed: %v", err) } log.Printf("Published without saving to history") // Publish with idempotency key for retry safety result, err = client.Publish(ctx, channel, messageData, gocent.WithIdempotencyKey("unique-message-id-123"), gocent.WithTags(map[string]string{ "source": "api", "priority": "high", })) if err != nil { log.Fatalf("Publish failed: %v", err) } log.Printf("Published with idempotency protection") // Publish with delta compression enabled result, err = client.Publish(ctx, channel, messageData, gocent.WithDelta(true), gocent.WithVersion(42), gocent.WithVersionEpoch("v1")) if err != nil { log.Fatalf("Publish failed: %v", err) } log.Printf("Published with delta compression support") } ``` -------------------------------- ### Retrieve channel history with Go (gocent) Source: https://context7.com/centrifugal/gocent/llms.txt Demonstrates how to retrieve message history from a Centrifugal channel with various options including pagination, reverse order, and filtering by position. Requires gocent v3 client library and valid API credentials. ```go package main import ( "context" "log" "github.com/centrifugal/gocent/v3" ) func main() { client := gocent.New(gocent.Config{ Addr: "http://localhost:8000/api", Key: "your-api-key-here", }) ctx := context.Background() channel := "chat:room1" // Get all history result, err := client.History(ctx, channel) if err != nil { log.Fatalf("History failed: %v", err) } log.Printf("Channel %s has %d messages", channel, len(result.Publications)) log.Printf("Current stream position - Offset: %d, Epoch: %s", result.Offset, result.Epoch) for _, pub := range result.Publications { log.Printf("Message at offset %d: %s", pub.Offset, string(pub.Data)) if pub.Info != nil { log.Printf(" Published by user: %s", pub.Info.User) } } // Get limited history (last 10 messages) result, err = client.History(ctx, channel, gocent.WithLimit(10)) if err != nil { log.Fatalf("History failed: %v", err) } log.Printf("Retrieved last %d messages", len(result.Publications)) // Get history in reverse order (oldest first) result, err = client.History(ctx, channel, gocent.WithLimit(10), gocent.WithReverse(true)) if err != nil { log.Fatalf("History failed: %v", err) } log.Printf("Retrieved oldest %d messages", len(result.Publications)) // Get history since specific position (for recovery) since := &gocent.StreamPosition{ Offset: 100, Epoch: "abc123", } result, err = client.History(ctx, channel, gocent.WithSince(since), gocent.WithLimit(gocent.NoLimit)) if err != nil { log.Fatalf("History failed: %v", err) } log.Printf("Retrieved %d messages since offset %d", len(result.Publications), since.Offset) // Get only current stream position without messages result, err = client.History(ctx, channel, gocent.WithLimit(0)) if err != nil { log.Fatalf("History failed: %v", err) } log.Printf("Current stream position: offset=%d, epoch=%s", result.Offset, result.Epoch) } ``` -------------------------------- ### Broadcast to Multiple Channels using Go Source: https://context7.com/centrifugal/gocent/llms.txt Broadcast identical data to multiple channels simultaneously in a single API call using the gocent client. This function takes a list of channels and the data to be broadcast, returning publish results for each channel. Options like skipping history or adding tags can be applied. ```go package main import ( "context" "encoding/json" "log" "github.com/centrifugal/gocent/v3" ) func main() { client := gocent.New(gocent.Config{ Addr: "http://localhost:8000/api", Key: "your-api-key-here", }) ctx := context.Background() // Broadcast announcement to multiple channels channels := []string{ "chat:lobby", "chat:room1", "chat:room2", "notifications:global", } announcement := map[string]interface{}{ "type": "system", "message": "Server maintenance in 10 minutes", "level": "warning", } announcementData, _ := json.Marshal(announcement) result, err := client.Broadcast(ctx, channels, announcementData) if err != nil { log.Fatalf("Broadcast failed: %v", err) } // Check each channel's publish result for i, resp := range result.Responses { if resp.Error != nil { log.Printf("Failed to broadcast to %s: %v", channels[i], resp.Error) } else { log.Printf("Successfully broadcast to %s, offset: %d, epoch: %s", channels[i], resp.Result.Offset, resp.Result.Epoch) } } // Broadcast with options result, err = client.Broadcast(ctx, channels, announcementData, gocent.WithSkipHistory(false), gocent.WithTags(map[string]string{"type": "broadcast"})) if err != nil { log.Fatalf("Broadcast failed: %v", err) } log.Printf("Broadcast completed to %d channels", len(channels)) } ``` -------------------------------- ### Disconnect User from Server with gocent Source: https://context7.com/centrifugal/gocent/llms.txt Forcefully disconnects a user from the server, closing all their active connections. Supports basic disconnects, custom messages, reconnect advice, specific client disconnects, and whitelisting. ```go package main import ( "context" "log" "github.com/centrifugal/gocent/v3" ) func main() { client := gocent.New(gocent.Config{ Addr: "http://localhost:8000/api", Key: "your-api-key-here", }) ctx := context.Background() userID := "user123" // Basic disconnect (all user connections) err := client.Disconnect(ctx, userID) if err != nil { log.Fatalf("Disconnect failed: %v", err) } log.Printf("User %s disconnected", userID) // Disconnect with custom disconnect message customDisconnect := &gocent.Disconnect{ Code: 4000, Reason: "Account suspended", Reconnect: false, } err = client.Disconnect(ctx, userID, gocent.WithDisconnect(customDisconnect)) if err != nil { log.Fatalf("Disconnect failed: %v", err) } log.Printf("User disconnected with custom message") // Disconnect with reconnect advice softDisconnect := &gocent.Disconnect{ Code: 3000, Reason: "Server maintenance", Reconnect: true, } err = client.Disconnect(ctx, userID, gocent.WithDisconnect(softDisconnect)) if err != nil { log.Fatalf("Disconnect failed: %v", err) } log.Printf("User disconnected but can reconnect") // Disconnect specific client while keeping others err = client.Disconnect(ctx, userID, gocent.WithDisconnectClient("client-connection-id-789")) if err != nil { log.Fatalf("Disconnect failed: %v", err) } log.Printf("Specific client connection disconnected") // Disconnect all except whitelisted clients whitelist := []string{"client-id-1", "client-id-2"} err = client.Disconnect(ctx, userID, gocent.WithDisconnectClientWhitelist(whitelist)) if err != nil { log.Fatalf("Disconnect failed: %v", err) } log.Printf("User disconnected except whitelisted clients") } ``` -------------------------------- ### Remove channel history with Go (gocent) Source: https://context7.com/centrifugal/gocent/llms.txt Shows how to delete all historical messages from a Centrifugal channel. Requires gocent v3 client library and valid API credentials. This operation is irreversible. ```go package main import ( "context" "log" "github.com/centrifugal/gocent/v3" ) func main() { client := gocent.New(gocent.Config{ Addr: "http://localhost:8000/api", Key: "your-api-key-here", }) ctx := context.Background() channel := "chat:temp" // Remove all history from channel err := client.HistoryRemove(ctx, channel) if err != nil { log.Fatalf("HistoryRemove failed: %v", err) } log.Printf("History removed from channel %s", channel) } ``` -------------------------------- ### Unsubscribe User from Channel with Go Source: https://context7.com/centrifugal/gocent/llms.txt Remove a user's subscription from a specific channel using the gocent client. This function can be used to unsubscribe a user by their ID or by a specific client connection ID. It requires a context, channel name, and user ID. ```go package main import ( "context" "log" "github.com/centrifugal/gocent/v3" ) func main() { client := gocent.New(gocent.Config{ Addr: "http://localhost:8000/api", Key: "your-api-key-here", }) ctx := context.Background() channel := "chat:room1" userID := "user123" // Unsubscribe user from channel err := client.Unsubscribe(ctx, channel, userID) if err != nil { log.Fatalf("Unsubscribe failed: %v", err) } log.Printf("User %s unsubscribed from %s", userID, channel) // Unsubscribe with specific client ID err = client.Unsubscribe(ctx, channel, userID, gocent.WithUnsubscribeClient("client-connection-id-456")) if err != nil { log.Fatalf("Unsubscribe failed: %v", err) } log.Printf("Specific client connection unsubscribed") } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.