# Go backends with Hibira: realtime features without running a WebSocket server

> Publish events, authorize private and presence channels and verify webhooks from Go with the official pusher-http-go library, while browsers connect to Hibira.

Source: https://hibira.io/blog/go-backend-realtime
Updated: 2026-11-20

Go is a great language for WebSocket servers, so many teams' first instinct is to build one: a hub, a goroutine per connection, broadcast whenever an event comes in. On one machine that works nicely. Once you run two or more, add presence (who is online), and handle reconnects and moving connections during deploys, WebSockets stop being a feature and become a system you operate.

The other way is to let your Go backend decide what to send, and leave holding tens of thousands of connections to a hosted service. Hibira speaks the Pusher Channels protocol, so you can use Pusher's official Go library, [pusher-http-go](https://github.com/pusher/pusher-http-go), with pusher-js in the browser. This post covers five things: creating the client, publishing events, authorizing private and presence channels, connecting the front end, and receiving webhooks.

```text
flow: Your Go backend publishes over HTTP; browsers receive over WebSocket
Your Go service --HTTP API--> *Hibira|ws.hibira.io --WebSocket--> Browsers and apps
Browsers and apps --on private subscribe--> /pusher/auth|your Go service
*Hibira --Webhook--> /pusher/webhook|your Go service
```

## Step 1: Install and create the client

```shell
go get github.com/pusher/pusher-http-go/v5
```

Create one client at startup from environment variables holding the app ID, key and secret (you'll see them once you [create an app](https://hibira.io/signup)), then pass it to the handlers or services that publish:

```go
import pusher "github.com/pusher/pusher-http-go/v5"

func newRealtime() *pusher.Client {
	return &pusher.Client{
		AppID:  os.Getenv("HIBIRA_APP_ID"),
		Key:    os.Getenv("HIBIRA_APP_KEY"),
		Secret: os.Getenv("HIBIRA_APP_SECRET"),
		Host:   "ws.hibira.io",
		Secure: true,
		// Set it at startup instead of letting the library create one on the first request
		HTTPClient: &http.Client{Timeout: 3 * time.Second},
	}
}
```

The `HTTPClient` line deserves a word. Without it, pusher-http-go creates an `http.Client` with a 5-second timeout on the first request and stores it on the client. If several goroutines publish for the first time at once, that is a data race, and `go test -race` will flag it. Set it yourself at startup, and pick a timeout that suits your service while you're at it.

## Step 2: Publish events

Publishing is one HTTP call. Take an order that ships:

```go
func shipOrder(rt *pusher.Client, w http.ResponseWriter, r *http.Request) {
	order := Order{ID: 1024, Status: "shipped"}
	// … write the new order status to the database first …

	socketID := r.Header.Get("X-Socket-ID") // sent by the front end, may be empty
	if err := rt.TriggerExclusive("private-user-42", "order-updated", order, socketID); err != nil {
		log.Printf("realtime: %v", err) // a failed publish doesn't undo the order
	}
	json.NewEncoder(w).Encode(order)
}
```

A few practical notes:

- **Write to the database first, then publish.** A realtime event is a notification, not the source of truth. A client that reconnects should reload from your API instead of relying on events it may have missed.
- **Leave out the sender.** Pass the front end's socket ID to `TriggerExclusive` and the tab that made the change won't get its own update back. When everyone should get it, plain `Trigger` is enough.
- **Send many at once.** When one request updates several channels, use `TriggerMulti` (the same event to many channels) or `TriggerBatch` (different events) to save round trips.
- **Don't hold up the request.** If publishing sits on a latency-sensitive path, hand it to a background goroutine or a job queue, but still handle errors and drain it on shutdown.

**Security note:** Treat `X-Socket-ID` as an optional echo-suppression hint, never as proof of the caller's identity. Authorize channels using your authenticated session, validate the form body, and reject oversized requests rather than silently truncating them.

## Step 3: Authorize private and presence channels

Before subscribing to a channel starting with `private-` or `presence-`, the client asks your server for a signature. Your Go service serves that endpoint, so who can see which channel is entirely up to your code:

```go
func pusherAuth(rt *pusher.Client) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		user, ok := currentUser(r) // your own session or JWT check
		if !ok {
			http.Error(w, "unauthorized", http.StatusUnauthorized)
			return
		}
		body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 4096))
		if err != nil {
			http.Error(w, "bad request", http.StatusBadRequest)
			return
		}
		form, err := url.ParseQuery(string(body))
		if err != nil {
			http.Error(w, "bad request", http.StatusBadRequest)
			return
		}
		channel := form.Get("channel_name")
		if (!strings.HasPrefix(channel, "private-") && !strings.HasPrefix(channel, "presence-")) || !user.CanJoin(channel) {
			http.Error(w, "forbidden", http.StatusForbidden)
			return
		}

		var resp []byte
		if strings.HasPrefix(channel, "presence-") {
			resp, err = rt.AuthorizePresenceChannel(body, pusher.MemberData{
				UserID:   user.ID,
				UserInfo: map[string]string{"name": user.Name},
			})
		} else {
			resp, err = rt.AuthorizePrivateChannel(body)
		}
		if err != nil {
			http.Error(w, "forbidden", http.StatusForbidden)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		w.Write(resp)
	}
}
```

The library only signs; it doesn't check permissions, so you must write the `CanJoin` step yourself. A common mistake is checking only that someone is signed in, which lets any signed-in user subscribe to `private-user-42`. A presence channel's `UserInfo` is sent to every member of the channel, so put only what may be shared in it.

Wire the three endpoints with the `http.ServeMux` patterns from Go 1.22 on:

```go
rt := newRealtime()
mux := http.NewServeMux()
mux.HandleFunc("POST /orders/{id}/ship", func(w http.ResponseWriter, r *http.Request) { shipOrder(rt, w, r) })
mux.HandleFunc("POST /pusher/auth", pusherAuth(rt))
mux.HandleFunc("POST /pusher/webhook", pusherWebhook(rt))
log.Fatal(http.ListenAndServe(":8080", mux))
```

## Step 4: Connect the front end

In the browser, point pusher-js at Hibira and its authorization endpoint at your Go service:

```js
import Pusher from 'pusher-js';

const pusher = new Pusher('your-app-key', {
  cluster: 'hkg',
  wsHost: 'ws.hibira.io',
  wsPort: 443,
  wssPort: 443,
  forceTLS: true,
  enabledTransports: ['ws', 'wss'],
  channelAuthorization: { endpoint: '/pusher/auth', transport: 'ajax' },
});

pusher.subscribe('private-user-42').bind('order-updated', (order) => {
  renderOrder(order);
});

// Send the socket ID with your own API calls so the server can skip this tab
await fetch('/orders/1024/ship', {
  method: 'POST',
  headers: { 'X-Socket-ID': pusher.connection.socket_id },
});
```

The authorization request carries the browser's cookies, so if the front end and your Go service share a domain, your existing session just works. With JWTs, add an `Authorization` header under `channelAuthorization.headers`. Mobile apps work the same way: PusherSwift and pusher-java-client both take a host and an authorization endpoint.

## Step 5: Receive webhooks

To learn when a channel gets its first subscriber, or who joined or left a presence channel, set a webhook URL on your app's page. pusher-http-go checks the `X-Pusher-Key` header and the HMAC signature for you:

```go
func pusherWebhook(rt *pusher.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, "bad request", http.StatusBadRequest)
			return
		}
		hook, err := rt.Webhook(r.Header, body) // checks X-Pusher-Key and the signature
		if err != nil {
			http.Error(w, "invalid signature", http.StatusUnauthorized)
			return
		}
		for _, e := range hook.Events {
			switch e.Name {
			case "member_added":
				markOnline(e.UserID)
			case "member_removed":
				markOffline(e.UserID)
			}
		}
		w.WriteHeader(http.StatusOK)
	}
}
```

Webhooks gather the events of a short window into one request. If your endpoint doesn't answer with a 2xx, Hibira retries for up to five minutes, so make handling idempotent: getting the same `member_added` twice should end the same way. If processing is slow, answer 200 first and hand the work to a background job.

## Before you go live

- Run the code that publishes under `go test -race`.
- Private channel authorization checks whether this user may see this channel, not only whether they are signed in.
- The app secret lives only in environment variables or a secret manager, never in version control or front-end code.
- In the debug console on your app's page, check that your events, subscriptions and webhooks show up.

The basic Go setup is also in the [Go integration guide](https://hibira.io/guides/go), which fills in your host when opened from your app's page. For push notifications, the [push notifications guide](https://hibira.io/guides/push-notifications) has a Go example. For whole scenarios, see [order tracking](https://hibira.io/use-cases/order-tracking) and [collaboration and presence](https://hibira.io/use-cases/collaboration-presence). If you write code with Claude Code or another AI assistant, it can fetch the Go integration guide through the [Hibira MCP server](https://hibira.io/mcp-server) and update your project for you.
