Go
Publish events, sign channel and user auth, validate webhooks, read history, manage versioned messages, and run push workflows from net/http services with the Go server SDK.
sockudo-http-go is the official Go server SDK for Sockudo, published as the module
github.com/sockudo/sockudo/server-sdks/sockudo-http-go/v2 (package sockudo). It is a trusted
backend library: it holds your app secret, signs every HTTP API request, and produces the
signatures your realtime clients need to join private and presence channels. It depends only on
the standard library and golang.org/x/crypto.
What it does in Go:
- Signed HTTP publishing to one channel, many channels, or a batch, with idempotency keys and a
built-in retry for network failures and
5xxresponses. - Private, presence, and encrypted channel authorization, user authentication, sending to a user, and user connection termination.
- Webhook signature validation from raw body bytes, with automatic decryption of encrypted channel events.
- Channel state, durable history, presence history, and presence snapshots.
- Versioned message reads and mutations (get, versions, update, delete, append) and annotations.
- Push notifications: device registrations, channel push subscriptions, publish, schedule, status, provider credentials, and typed Apple Live Activity payloads and broadcast channels.
Install
go get github.com/sockudo/sockudo/server-sdks/sockudo-http-go/v2@v2.2.0The module lives in a subdirectory of the Sockudo monorepo, so its releases are tagged
server-sdks/sockudo-http-go/v2.2.0; go get resolves @v2.2.0 to that tag. The module’s
go.mod declares go 1.25.0, so you need Go 1.25 or later.
import sockudo "github.com/sockudo/sockudo/server-sdks/sockudo-http-go/v2"Configure the client
Build one *sockudo.Client at startup and share it across handlers and goroutines:
package main
import ( "net/http" "os" "time"
sockudo "github.com/sockudo/sockudo/server-sdks/sockudo-http-go/v2")
func newSockudoClient() *sockudo.Client { return &sockudo.Client{ AppID: os.Getenv("SOCKUDO_APP_ID"), Key: os.Getenv("SOCKUDO_APP_KEY"), Secret: os.Getenv("SOCKUDO_APP_SECRET"), Host: os.Getenv("SOCKUDO_HOST"), // "127.0.0.1:6001" or "realtime.example.com" Secure: os.Getenv("SOCKUDO_USE_TLS") != "false",
// Match the server's default 100 KB payload limit (the SDK checks 10 KB otherwise). OverrideMaxMessagePayloadKB: 100,
HTTPClient: &http.Client{ Timeout: 5 * time.Second, Transport: &http.Transport{ MaxIdleConns: 100, MaxIdleConnsPerHost: 20, IdleConnTimeout: 90 * time.Second, }, }, }}| Field | Type | Default | Description |
|---|---|---|---|
AppID | string | — | Sockudo app ID. |
Key | string | — | App key. Sent with every signed request and embedded in auth signatures. |
Secret | string | — | App secret. Signs API requests, channel auth, and user auth. |
Host | string | localhost | API host, or host:port, without a scheme. Used as-is when set. |
Secure | bool | false | Use HTTPS. Set true outside a trusted local network. |
Cluster | string | — | Builds api-CLUSTER.sockudo.com when Host is empty. Not needed for self-hosted servers. |
HTTPClient | *http.Client | &http.Client{Timeout: 5 * time.Second} | Client used for every request. The default is created on first use. |
EncryptionMasterKeyBase64 | string | — | Base64 of a 32-byte key for private-encrypted-* channels. |
EncryptionMasterKey | string | — | Deprecated raw 32-byte key. Setting both key fields is an error. |
OverrideMaxMessagePayloadKB | int | 0 (10 KB check) | Client-side payload size check per event, in KB. |
AutoIdempotencyKey | *bool | nil (enabled) | Generate idempotency keys for publishes that do not set one. |
You can also parse a connection URL. The path must be /apps/APP_ID with a numeric app ID, and
an https scheme sets Secure:
// SOCKUDO_URL=https://APP_KEY:APP_SECRET@realtime.example.com/apps/12345client, err := sockudo.ClientFromEnv("SOCKUDO_URL")if err != nil { // Parse errors can echo the URL, which contains the secret; do not log err verbatim. log.Fatal("sockudo config: invalid SOCKUDO_URL")}
// Or parse any string you choose:// client, err := sockudo.ClientFromURL(os.Getenv("REALTIME_URL"))Publish an event
data := map[string]any{"id": "ord_123", "total_cents": 4200}
if err := client.Trigger("private-orders-42", "order.created", data); err != nil { return fmt.Errorf("publish order.created: %w", err)}Trigger returns only an error. Use TriggerWithParams to pass options; it returns a
*sockudo.TriggerChannelsList whose Channels map is filled when you request attributes with
Info (for example "user_count" on presence channels). Data that is not a string or []byte
is encoded with encoding/json.
Exclude the originating connection when the publish comes from a user action that already updated that browser tab. The server skips that one connection, so the user does not receive an echo of their own change:
params := sockudo.TriggerParams{}if socketID := r.FormValue("socket_id"); socketID != "" { params.SocketID = &socketID // must look like "123.456"}
_, err := client.TriggerWithParams("private-orders-42", "order.updated", data, params)if err != nil { return err}TriggerParams.Extras carries Protocol V2 publish extras (Headers, Ephemeral, Echo,
IdempotencyKey) as a *sockudo.MessageExtras.
Publish to many channels or in a batch
TriggerMulti and TriggerMultiWithParams publish the same event to several channels in one
request:
channels := []string{"tenant-42-orders", "user-7-orders"}key := "order.updated:tenant-42:ord_123:v3"
_, err := client.TriggerMultiWithParams(channels, "order.updated", data, sockudo.TriggerParams{ IdempotencyKey: &key,})if err != nil { return err}TriggerBatch sends different events in one request and returns a
*sockudo.TriggerBatchChannelsList:
createdKey := "order.created:ord_124"receiptKey := "order.receipt:ord_124"
_, err := client.TriggerBatch([]sockudo.Event{ {Channel: "orders", Name: "order.created", Data: map[string]string{"id": "ord_124"}, IdempotencyKey: &createdKey}, {Channel: "private-user-7", Name: "order.receipt", Data: map[string]string{"id": "ord_124"}, IdempotencyKey: &receiptKey},})if err != nil { return err}Before sending, the SDK returns an error when a publish names more than 100 channels, when a
channel name is invalid (letters, digits, and -_=@,.;:, at most 200 characters), when a socket
ID is malformed, when a multi-channel publish includes a private-encrypted-* channel, or when an
event’s data exceeds the local payload check (10 KB unless OverrideMaxMessagePayloadKB is set).
It does not cap batch size. The server enforces its [event_limits] defaults:
| Limit | Default |
|---|---|
max_channels_at_once | 100 channels per publish |
max_batch_size | 10 events per batch |
max_payload_in_kb | 100 KB per event payload |
max_name_length | 200 characters per event or channel name |
Idempotency and retries
A timeout does not tell you whether the server published the event. If you retry without a key,
subscribers can receive the event twice. An idempotency key makes the retry safe: within the TTL,
the server returns the original cached response (200) instead of publishing again.
Server semantics:
- The key can be sent as the body field
idempotency_keyor theX-Idempotency-Keyheader. The body field takes precedence. [idempotency]defaults areenabled = true,ttl_seconds = 120, andmax_key_length = 128. Empty keys are rejected.- In a batch,
X-Idempotency-Keyidentifies the whole batch and each event’sidempotency_keyidentifies only that event. The two key domains do not collide. - If the coordination backend is unavailable, the server returns
503 service_unavailable. A concurrent retry while the first attempt is still in flight gets503 backpressurewithRetry-After: 1. Retry both with the same key.
How the Go SDK applies keys:
- Set
TriggerParams.IdempotencyKey. The SDK sends it as both the body field and theX-Idempotency-Keyheader. - In
TriggerBatch, setEvent.IdempotencyKeyon each event. The SDK does not send a batch-level header, and it writes generated keys back into the slice you pass. - When
AutoIdempotencyKeyis unset or true, publishes without a key get a generated one in the formBASE:N(andBASE:N:INDEXfor batch events), whereBASEis random per client. That key protects only the SDK’s own retry of the same call; a new call, process, or job attempt gets a new key. Disable it with afalsepointer. Trigger*,TriggerBatch,TerminateUserConnections, andForceReconnectUsermake up to 3 attempts in total when the request fails at the network level or the server answers5xx. The retries are immediate, without backoff, and ignoreRetry-After.4xxresponses, including429, are returned without a retry.
For retries you control, derive the key from the logical operation so every attempt shares it:
func publishOrderPaid(client *sockudo.Client, orderID string, version int) error { key := fmt.Sprintf("order.paid:%s:v%d", orderID, version) _, err := client.TriggerWithParams( "private-orders-"+orderID, "order.paid", map[string]any{"id": orderID, "version": version}, sockudo.TriggerParams{IdempotencyKey: &key}, ) return err}sockudo.GenerateIdempotencyKey() returns a random UUID v4. If you use it, generate it once when
you create the job and store it with the job.
Authorize private and presence channels
When a client subscribes to a private-* or presence-* channel, it asks your backend for a
signature. Your handler decides whether the current user may join; the SDK only signs the answer.
For presence channels, take the user ID and info from your own session, never from the request, or
any user could claim to be anyone.
The client posts socket_id and channel_name form-encoded. The SDK parses that body itself, so
read it once, inspect the channel, and pass the same bytes on:
func sockudoAuth(client *sockudo.Client) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { user, ok := currentUser(r) // your session lookup if !ok { http.Error(w, "unauthenticated", http.StatusUnauthorized) return }
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 4<<10)) if err != nil { http.Error(w, "invalid body", http.StatusBadRequest) return } form, err := url.ParseQuery(string(body)) if err != nil { http.Error(w, "invalid body", http.StatusBadRequest) return }
channel := form.Get("channel_name") if !canSubscribe(user, channel) { // your authorization rules http.Error(w, "forbidden", http.StatusForbidden) return }
var response []byte if strings.HasPrefix(channel, "presence-") { response, err = client.AuthorizePresenceChannel(body, sockudo.MemberData{ UserID: user.ID, UserInfo: map[string]string{"name": user.DisplayName}, }) } else { response, err = client.AuthorizePrivateChannel(body) } if err != nil { // Missing fields, malformed socket_id, or a missing encryption key. http.Error(w, "bad request", http.StatusBadRequest) return }
w.Header().Set("Content-Type", "application/json") w.Write(response) }}http.HandleFunc("POST /sockudo/auth", sockudoAuth(client))The response is JSON bytes: {"auth":"KEY:SIGNATURE"} for private channels, plus channel_data
for presence channels and shared_secret for encrypted channels. MemberData.UserInfo is a
map[string]string.
User authentication
User authentication (sign-in) binds a connection to a user ID so the server can target that user and terminate their connections:
func sockudoUserAuth(client *sockudo.Client) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { user, ok := currentUser(r) if !ok { http.Error(w, "unauthenticated", http.StatusUnauthorized) return } body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 4<<10)) if err != nil { http.Error(w, "invalid body", http.StatusBadRequest) return }
response, err := client.AuthenticateUser(body, map[string]any{ "id": user.ID, // must be a non-empty string "name": user.DisplayName, }) if err != nil { http.Error(w, "bad request", http.StatusBadRequest) return } w.Header().Set("Content-Type", "application/json") w.Write(response) }}The response is {"auth":"...","user_data":"..."}. To publish to every authenticated connection of
one user, call client.SendToUser(userID, eventName, data).
Encrypted channels
private-encrypted-* channels are end-to-end encrypted: the server relays ciphertext it cannot
read. Generate a 32-byte key and set EncryptionMasterKeyBase64:
openssl rand -base64 32client := &sockudo.Client{ AppID: os.Getenv("SOCKUDO_APP_ID"), Key: os.Getenv("SOCKUDO_APP_KEY"), Secret: os.Getenv("SOCKUDO_APP_SECRET"), Host: os.Getenv("SOCKUDO_HOST"), Secure: true, EncryptionMasterKeyBase64: os.Getenv("SOCKUDO_ENCRYPTION_MASTER_KEY"),}The SDK encrypts event data with a per-channel key derived from the master key, adds that
channel’s shared_secret to auth responses, and decrypts encrypted channel events in validated
webhooks. Publish to one encrypted channel per call: multi-channel publishes that include an
encrypted channel return an error. Batches may contain encrypted events. The key must decode to
exactly 32 bytes.
Terminate user connections
When access changes, disconnect a user’s sockets immediately:
if err := client.TerminateUserConnections(user.ID); err != nil { return err}
// Or close every socket with code 4200 so clients reconnect and re-authenticate:if err := client.ForceReconnectUser(user.ID); err != nil { return err}Validate webhooks
Sockudo signs each webhook with HMAC-SHA256 over the exact request body bytes and sends the result
in X-Pusher-Signature, with the app key in X-Pusher-Key. Validation must see the raw body:
decoding and re-encoding the JSON changes the bytes and breaks the signature. Read the body with
io.ReadAll and pass those bytes unchanged:
func sockudoWebhook(client *sockudo.Client) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20)) if err != nil { http.Error(w, "invalid body", http.StatusBadRequest) return }
webhook, err := client.Webhook(r.Header, body) if err != nil { http.Error(w, "invalid webhook", http.StatusUnauthorized) return }
// Acknowledge fast; process the events on a queue. enqueueWebhookEvents(webhook.Events) w.WriteHeader(http.StatusOK) }}Webhook compares signatures in constant time and returns an error for an unknown key, a bad
signature, malformed JSON, or an encrypted event without a configured master key. A valid
*sockudo.Webhook has TimeMs and Events; each WebhookEvent has Name, Channel, Event,
Data, SocketID, and UserID, plus RawData and Fields that preserve the original JSON for
nested data and future fields.
Sockudo may deliver the same webhook more than once, so process events idempotently. The SDK validates against a single key pair. To accept both keys during a rotation, keep a second client configured with the previous key and secret and try it when the first returns an error.
Channel state and history
prefix := "presence-"info := "user_count"channels, err := client.Channels(sockudo.ChannelsParams{FilterByPrefix: &prefix, Info: &info})if err != nil { return err}
attrs := "user_count,subscription_count"lobby, err := client.Channel("presence-lobby", sockudo.ChannelParams{Info: &attrs})if err != nil { return err}
users, err := client.GetChannelUsers("presence-lobby") // users.List []User{ID}State is an operational snapshot at the moment of the request; never use it as an authorization source.
ChannelHistory returns a *sockudo.HistoryPage with Items, HasMore, NextCursor, Bounds,
and Continuity. HistoryParams supports Limit, Direction ("newest_first" or
"oldest_first"), Cursor, StartSerial, EndSerial, StartTimeMS, and EndTimeMS:
limit := 100direction := "oldest_first"params := sockudo.HistoryParams{Limit: &limit, Direction: &direction}
for { page, err := client.ChannelHistory("orders", params) if err != nil { return err } for _, item := range page.Items { export(item) } if !page.HasMore || page.NextCursor == nil { break } params.Cursor = page.NextCursor}Cursors are opaque: pass NextCursor back unchanged and do not parse or construct them. The server
caps page sizes, so keep Limit bounded.
Presence history records join and leave transitions, and a snapshot rebuilds membership at a serial
or timestamp. Both reject channel names without the presence- prefix before sending:
limit := 50direction := "newest_first"transitions, err := client.ChannelPresenceHistory("presence-lobby", sockudo.PresenceHistoryParams{ Limit: &limit, Direction: &direction,})
serial := int64(4)snapshot, err := client.ChannelPresenceSnapshot("presence-lobby", sockudo.PresenceSnapshotParams{ AtSerial: &serial, // or AtTimeMS})The Go SDK has no exported generic signed-request helper; every supported endpoint has its own method.
Versioned messages and annotations
Protocol V2 messages can be read and mutated after publish. The SDK wraps the HTTP surface
described in Mutable messages. Mutation bodies are any value that
encoding/json can marshal, using the server’s snake_case fields:
latest, err := client.GetMessage("chat-room-1", messageSerial) // latest.Item
limit := 20versions, err := client.GetMessageVersions("chat-room-1", messageSerial, sockudo.MessageVersionsParams{ Limit: &limit,})
updated, err := client.UpdateMessage("chat-room-1", messageSerial, map[string]any{ "data": "hello, edited", "description": "fix typo", "op_id": "edit:" + messageSerial + ":2",})if err != nil { return err}log.Printf("message %s: %s (accepted=%t)", updated.MessageSerial, updated.Status, updated.Accepted)
_, err = client.AppendMessage("chat-room-1", messageSerial, map[string]any{"data": " more text"})_, err = client.DeleteMessage("chat-room-1", messageSerial, map[string]any{"description": "removed"})MutationResponse exposes Channel, MessageSerial, Action, Accepted, Status,
VersionSerial, HistorySerial, and DeliverySerial. op_id makes a mutation idempotent:
replaying the same ID with the same operation returns the original acknowledgement. Without
socket_id, a signed app-key request is a privileged server operation.
Annotations attach typed reactions or flags to a message:
name := "thumbs_up"created, err := client.PublishAnnotation("chat-room-1", messageSerial, sockudo.PublishAnnotationRequest{ Type: "reactions:distinct.v1", Name: &name,})if err != nil { return err}
annotationType := "reactions:distinct.v1"events, err := client.ListAnnotations("chat-room-1", messageSerial, sockudo.AnnotationEventsParams{ Type: &annotationType,})
_, err = client.DeleteAnnotation("chat-room-1", messageSerial, created.AnnotationSerial, nil)Push notifications
The push helpers sign /apps/APP_ID/push/* requests and send the push capability header for you
(push-admin by default, push-subscribe when you pass a device identity token). Request types
such as PushDeviceDetails and PushPublishRequest are map[string]interface{} in the server’s
camelCase shape, and every method returns the raw JSON response as []byte. See
Push notifications for the full model.
Register a device from your backend after you verify the user:
raw, err := client.ActivateDevice(sockudo.PushDeviceDetails{ "appId": os.Getenv("SOCKUDO_APP_ID"), "id": deviceID, "clientId": user.ID, "formFactor": "phone", "platform": "android", "deviceSecret": "admin-registration-placeholder", "timezone": "UTC", "locale": "en", "push": map[string]any{ "recipient": map[string]any{"transportType": "gcm", "registrationToken": fcmToken}, "state": "ACTIVE", },})if err != nil { return err}
var registration struct { TokenHash string `json:"tokenHash"` DeviceIdentityToken string `json:"deviceIdentityToken"`}if err := json.Unmarshal(raw, ®istration); err != nil { return err}With admin capability the server ignores the deviceSecret value and issues a device identity
token on first registration. Store it for device-scoped calls such as UpdateDeviceRegistration.
Subscribe the device to a channel, publish, and check status:
_, err = client.UpsertChannelPushSubscription(sockudo.PushChannelSubscription{ "appId": os.Getenv("SOCKUDO_APP_ID"), "channel": "private-orders-42", "deviceId": deviceID, "clientId": user.ID, "provider": "fcm", "tokenHash": registration.TokenHash,}, "")if err != nil { return err}
raw, err = client.PublishPush(sockudo.PushPublishRequest{ "publishId": "push:order-ord_123:packed", "recipients": []sockudo.PushRecipient{{"type": "channel", "channel": "private-orders-42"}}, "payload": map[string]any{"title": "Order updated", "body": "Order ord_123 is packed"},})if err != nil { return err}
var accepted struct { PublishID string `json:"publishId"` Status string `json:"status"`}if err := json.Unmarshal(raw, &accepted); err != nil { return err}
status, err := client.GetPublishStatus(accepted.PublishID)PublishPush sets "sync": false on the map you pass. The 202 response is an admission record
(publishId, status, expectedRecipients), not proof of delivery; inspect delivery
asynchronously with GetPublishStatus. Reuse the same publishId when you retry a publish.
Other push methods:
| Area | Methods |
|---|---|
| Devices | ActivateDevice (alias CreateDeviceActivation), UpdateDeviceRegistration, GetDeviceRegistration, ListDeviceRegistrations, DeleteDeviceRegistration, RemoveDeviceRegistrationsByClient |
| Subscriptions | UpsertChannelPushSubscription, ListChannelPushSubscriptions, DeleteChannelPushSubscriptions, ListChannelPushSubscriptionChannels |
| Publishing | PublishPush (alias PublishPushDirect), PublishPushBatch, SchedulePush (requires notBeforeMs), CancelScheduledPush, GetPublishStatus, PostPushDeliveryStatus |
| Credentials | PutPushCredential, ListPushCredentials |
For Apple Live Activities, ApnsLiveActivityPayload with NewApnsLiveActivityRecipient and
NewApnsLiveActivityBroadcastRecipient provide the typed ActivityKit wire contract. Manage iOS 18
broadcast channels with CreateApnsLiveActivityChannel (sockudo.ApnsChannelNoStorage or
sockudo.ApnsChannelMostRecent), GetApnsLiveActivityChannel, ListApnsLiveActivityChannels,
and DeleteApnsLiveActivityChannel. See Apple Live Activities
for lifecycle rules.
Errors and timeouts
Every network operation returns an error; check it before using the result. The SDK has no typed
error values:
- Transport failures (connection refused, DNS, TLS, timeouts) are the
*url.Errorreturned byhttp.Client.Do. - Non-
2xxresponses are plain errors whose message isStatus Code: NNN - RESPONSE_BODY. - Local validation failures (channel names, socket IDs, payload size, missing encryption key) are plain errors returned before any request is sent.
Retry network errors, 429, and 5xx with bounded backoff and the original idempotency key. Do
not retry 400, 401, 403, or 413: the same request fails the same way.
func sockudoStatus(err error) int { var code int if _, scanErr := fmt.Sscanf(err.Error(), "Status Code: %d", &code); scanErr != nil { return 0 } return code}
func retryable(err error) bool { var urlErr *url.Error if errors.As(err, &urlErr) { return true } code := sockudoStatus(err) return code == http.StatusTooManyRequests || code >= 500}
func handleOrderPaid(client *sockudo.Client, orderID string, version int) error { err := publishOrderPaid(client, orderID, version) if err != nil && retryable(err) { return scheduleRetry(orderID, version) // same key on the next attempt } return err}The HTTPClient timeout (5 seconds by default) bounds each attempt, and the built-in retry can
make up to 3 attempts, so keep 3 x timeout below the enclosing request or job deadline.