hibira

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 19 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Hibira for Go

Go packages for Hibira, hosted realtime that speaks the Pusher Channels protocol. Stream LLM output to the browser, publish events, authorize private and presence channels, verify webhooks, send push notifications, use the Chat API, ask a person for an approval and put a waiting room in front of a launch. pusher-js, Laravel Echo and the @hibira-io/* front-end packages connect unchanged.

go get github.com/hibira-io/go

The core module has no dependencies and needs Go 1.21 or later. Gin, Echo and Fiber each get a small module of their own, so you only download the framework you use.

Package What it does
github.com/hibira-io/go Client: publish events, channel info, channel authorization and user sign-in, webhooks, push notifications, Chat API. net/http handlers for the standard library, chi and gorilla/mux.
github.com/hibira-io/go/stream Stream an LLM's output to a channel as it is written, for useStream() in React and Vue.
github.com/hibira-io/go/approvals Ask a person for a decision from a server, job or agent with Hibira Approvals, wait for the answer and verify decision callbacks.
github.com/hibira-io/go/waitingroom Check waiting room passes and put the queue in front of any net/http handler.
github.com/hibira-io/go/livechat Verified visitors for the Hibira Live Chat widget.
github.com/hibira-io/go/gin Gin handlers and middleware for all of the above.
github.com/hibira-io/go/echo Echo v5 handlers and middleware.
github.com/hibira-io/go/fiber Fiber v3 handlers and middleware.

Set up

Create an app at hibira.io/portal (the free plan needs no card) and put its keys in the environment:

HIBIRA_APP_ID=...
HIBIRA_APP_KEY=...
HIBIRA_APP_SECRET=...
client := hibira.FromEnv()
err := client.Trigger(ctx, "orders", "created", map[string]any{"id": 1042})
Field Environment Default
AppID, Key, Secret HIBIRA_APP_ID, HIBIRA_APP_KEY, HIBIRA_APP_SECRET
Host HIBIRA_HOST (with HIBIRA_PORT, HIBIRA_USE_TLS) https://ws.hibira.io
PushInstanceID, PushSecretKey HIBIRA_PUSH_INSTANCE_ID, HIBIRA_PUSH_SECRET_KEY
PushEndpoint HIBIRA_PUSH_ENDPOINT Host
HTTPClient, Timeout http.DefaultClient, 10 s

Stream LLM output to the browser

A stream.Stream is an io.Writer: write each text delta from your LLM SDK as it arrives and Close at the end. Tokens are batched (about ten events a second), each event stays under the plan's message size, and the last event carries the whole text when it fits, so people who open the page late catch up.

import (
	hibira "github.com/hibira-io/go"
	"github.com/hibira-io/go/stream"
	"github.com/openai/openai-go"
)

s, _ := stream.New(ctx, client, "private-conversation-"+id, stream.Options{Meta: map[string]string{"role": "assistant"}})
res := llm.Chat.Completions.NewStreaming(ctx, params)
for res.Next() {
	if c := res.Current(); len(c.Choices) > 0 {
		s.WriteString(c.Choices[0].Delta.Content)
	}
}
if err := res.Err(); err != nil {
	s.Fail(err) // useStream() shows the error
} else {
	s.Close()
}
save(id, s.Text())
// React (@hibira-io/react)
const { text, done } = useStream(`private-conversation-${id}`);

The same loop works with any SDK that streams text deltas (Anthropic, Gemini, Bedrock, Ollama). stream.Copy(ctx, client, channel, deltas, opts) drains a <-chan string instead. Options: ID, Event (default ai-stream), Interval (100 ms), MaxBytes (3500; Free plans allow 4 KB per message), Meta and SocketID.

Authorize private and presence channels

mux.Handle("POST /hibira/auth", client.AuthHandler(func(r *http.Request, channel string) (bool, *hibira.Member) {
	u := currentUser(r)
	if u == nil {
		return false, nil
	}
	if channel == "private-user-"+u.ID {
		return true, nil
	}
	if strings.HasPrefix(channel, "presence-room-") {
		return true, &hibira.Member{UserID: u.ID, UserInfo: map[string]string{"name": u.Name}}
	}
	return false, nil
}))
mux.Handle("POST /hibira/user-auth", client.UserAuthHandler(func(r *http.Request) *hibira.User {
	if u := currentUser(r); u != nil {
		return &hibira.User{ID: u.ID}
	}
	return nil
}))

Point pusher-js at them with channelAuthorization.endpoint and userAuthentication.endpoint. AuthorizeChannel and AuthenticateUser sign without a handler, and make no network call.

Gin, Echo, Fiber
import hibiragin "github.com/hibira-io/go/gin"     // go get github.com/hibira-io/go/gin
import hibiraecho "github.com/hibira-io/go/echo"   // Echo v5
import hibirafiber "github.com/hibira-io/go/fiber" // Fiber v3

r.POST("/hibira/auth", hibiragin.Auth(client, func(c *gin.Context, channel string) (bool, *hibira.Member) { ... }))
r.POST("/hibira/user-auth", hibiragin.UserAuth(client, func(c *gin.Context) *hibira.User { ... }))
r.POST("/hibira/webhook", hibiragin.Webhook(client, onWebhook))
r.POST("/hibira/approvals", hibiragin.ApprovalCallback(os.Getenv("HIBIRA_APP_SECRET"), onDecision))
r.GET("/drop", hibiragin.WaitingRoom(room), dropPage) // hibiragin.Pass(c) inside

Each module has the same five functions, and your callbacks get the framework's own context. On Echo v4 or Fiber v2, mount the net/http handlers with echo.WrapHandler or Fiber's adaptor.HTTPHandler.

Webhooks

mux.Handle("POST /hibira/webhook", client.WebhookHandler(func(r *http.Request, hook *hibira.Webhook) error {
	for _, e := range hook.Events {
		log.Println(e.Name, e.Channel, e.UserID)
	}
	return nil // an error answers 500 and the delivery is retried
}))

client.VerifyWebhook(key, signature, body) checks a delivery anywhere else and returns an error wrapping hibira.ErrInvalidWebhook.

Channels API

client.Publish(ctx, hibira.Event{Channels: []string{"a", "b"}, Name: "e", Data: data, SocketID: socketID})
client.TriggerBatch(ctx, []hibira.BatchEvent{{Channel: "a", Name: "e", Data: data}})
client.Channels(ctx, "presence-", "user_count")
client.Channel(ctx, "presence-room-7", "user_count", "subscription_count")
client.Users(ctx, "presence-room-7")
client.TerminateUserConnections(ctx, "42")

Data that is not a string or []byte is sent as JSON.

Push notifications

Turn on Push for the app in the portal and set HIBIRA_PUSH_INSTANCE_ID and HIBIRA_PUSH_SECRET_KEY. Bodies use the Beams format.

client.PushToInterests(ctx, []string{"news"}, map[string]any{
	"web":  map[string]any{"notification": map[string]any{"title": "New post", "deep_link": "https://example.com/p/1"}},
	"fcm":  map[string]any{"notification": map[string]any{"title": "New post"}},
	"apns": map[string]any{"aps": map[string]any{"alert": map[string]any{"title": "New post"}}},
})
client.PushToUsers(ctx, []string{"42"}, body)
token, _ := client.PushToken("42", 24*time.Hour) // for setUserId in the web, Android and iOS SDKs
client.DeletePushUser(ctx, "42")

Chat API

Conversations with stored history, read receipts and offline push (reference). Clients receive chat.* events on #server-to-user-<user_id> after pusher.signin(), so add the user sign-in endpoint above.

client.PutConversation(ctx, "order-1042", hibira.ConversationInput{Name: "Order #1042", Members: []string{"cust_7", "agent_2"}})
client.SendMessage(ctx, "order-1042", hibira.MessageInput{UserID: "agent_2", Text: "Your parcel left the warehouse.", Push: "offline"})
page, _ := client.ListMessages(ctx, "order-1042", hibira.ListOptions{After: lastSeq, Limit: 50})
client.MarkRead(ctx, "order-1042", "cust_7", page.LastSeq)
client.UserConversations(ctx, "cust_7", 20, "") // latest first, each with Unread

Also GetConversation, DeleteConversation, AddMembers, RemoveMember, SystemMessage, Typing, NewChatToken, and ChatRequest for every other call (reactions, edits, search, moderation, translation).

Approvals

a, err := client.Approvals().Request(ctx, approvals.Request{Title: "Refund order #1042 for $89?", Options: []string{"Refund", "Decline"}})
// share a.URL, or set PushUsers / Channel / Approvers, then
a, err = client.Approvals().Wait(ctx, a.ID)
if err == nil && a.Approved() {
	refund(1042)
}

See approvals for callbacks and replies.

Waiting rooms

room := waitingroom.Guard{AppKey: os.Getenv("HIBIRA_APP_KEY"), Secret: []string{os.Getenv("HIBIRA_APP_SECRET")}, Room: "presale"}
http.Handle("/drop/", room.Middleware(dropHandler))

See waitingroom.

Live Chat verified visitors

tag, _ := livechat.Snippet(workspaceID, identitySecret, &livechat.Visitor{ID: u.ID, Name: u.Name, Email: u.Email})
// {{.LiveChat}} in an html/template page; or livechat.UserHash(identitySecret, u.ID)

Errors

API errors are *hibira.Error (Status, Message, Body); hibira.StatusOf(err) reads the status: 401/403 bad credentials, 404 unknown app or conversation, 413 the event is over the plan's message size, 429 rate limited. A missing setting wraps hibira.ErrConfig.

Releases

Module Tag
github.com/hibira-io/go vX.Y.Z
github.com/hibira-io/go/gin gin/vX.Y.Z
github.com/hibira-io/go/echo echo/vX.Y.Z
github.com/hibira-io/go/fiber fiber/vX.Y.Z

Releases are listed under Releases and in CHANGELOG.md. When a framework module needs a new core version, release the core first.

Development

gofmt -l .
go vet ./...
go test -race ./...
(cd gin && go test -race ./...)   # echo and fiber need Go 1.25

The framework modules replace github.com/hibira-io/go with ../, so they test against the core in the same commit.

TestE2E runs against a real server when HIBIRA_E2E=1 and the HIBIRA_* settings point at it, such as a local pusher-server started with STANDALONE_MODE=true PUSHER_APP_CHAT=true.

The waiting room tests check a pass signed by the Hibira server, the same test vector hibira-io/waiting-room uses. If the pass format changes, update it in both places.

License

MIT

中文摘要

Hibira 的 Go 套件都在這個 repo。核心模組 github.com/hibira-io/go 沒有外部相依(Go 1.21 以上),提供:發送事件與頻道查詢、私人 / presence 頻道授權與使用者登入(net/http handler,標準函式庫、chi、gorilla/mux 皆可用)、webhook 驗證、推播通知、Chat API。子套件 stream 把 LLM 的輸出即時串流到頻道,React / Vue 的 useStream() 直接接收;approvals 請人做決定;waitingroom 等候室;livechat 產生 Live Chat 已驗證訪客的簽章與 script 標籤。

Gin、Echo(v5)、Fiber(v3)各有獨立的小模組(/gin、/echo、/fiber),提供頻道授權、使用者登入、webhook、Approvals callback 與等候室 middleware,callback 拿到的是框架自己的 context。核心用 vX.Y.Z tag 發布,框架模組用 gin/vX.Y.Z 這類 tag;框架模組需要新核心時,先發布核心。

Documentation

Overview

Package hibira is the Go server library for Hibira (https://hibira.io), hosted realtime that speaks the Pusher Channels protocol: publish events, authorize private and presence channels, sign users in, verify webhooks, send push notifications and use the Chat API. pusher-js, Laravel Echo and the @hibira-io/* front-end packages connect to Hibira unchanged.

client := hibira.FromEnv() // HIBIRA_APP_ID, HIBIRA_APP_KEY, HIBIRA_APP_SECRET
err := client.Trigger(ctx, "orders", "created", map[string]any{"id": 1042})

The net/http handlers (AuthHandler, UserAuthHandler, WebhookHandler) work with the standard library, chi, gorilla/mux and anything else that takes an http.Handler. Gin, Echo and Fiber have their own modules under github.com/hibira-io/go/gin, /echo and /fiber.

Example
package main

import (
	"context"
	"log"

	hibira "github.com/hibira-io/go"
)

func main() {
	client := hibira.FromEnv() // HIBIRA_APP_ID, HIBIRA_APP_KEY, HIBIRA_APP_SECRET
	ctx := context.Background()
	if err := client.Trigger(ctx, "orders", "created", map[string]any{"id": 1042}); err != nil {
		log.Print(err)
	}
}

Index

Examples

Constants

View Source
const DefaultHost = "https://ws.hibira.io"

DefaultHost serves the Hibira HTTP API.

View Source
const DefaultTimeout = 10 * time.Second

DefaultTimeout is how long one API call may take unless Client.Timeout says otherwise.

View Source
const MaxTriggerChannels = 100

MaxTriggerChannels is how many channels one event may go to.

View Source
const MaxWebhookBody = 1 << 20

MaxWebhookBody is the largest webhook body the handlers read.

Variables

View Source
var ErrConfig = errors.New("hibira: missing setting")

ErrConfig is returned when a setting the call needs is missing.

View Source
var ErrInvalidWebhook = errors.New("hibira: invalid webhook")

ErrInvalidWebhook is returned by VerifyWebhook for a delivery whose key or signature does not match the app.

Functions

func StatusOf

func StatusOf(err error) int

StatusOf returns the HTTP status of an *Error in err's chain, or 0. 401/403: bad credentials; 404: unknown app, channel or conversation; 413: the event is over the plan's message size; 429: rate limited.

func WriteJSON

func WriteJSON(w http.ResponseWriter, status int, v any)

WriteJSON writes v as a JSON answer with status.

Types

type AuthRequest

type AuthRequest struct {
	SocketID string `json:"socket_id"`
	Channel  string `json:"channel_name"`
}

AuthRequest is what pusher-js sends to the channel authorization and user sign-in endpoints.

func ParseAuthRequest

func ParseAuthRequest(contentType string, body []byte) (AuthRequest, error)

ParseAuthRequest reads socket_id and channel_name from a request body with the given Content-Type: form-encoded (the pusher-js default) or JSON.

func ReadAuthRequest

func ReadAuthRequest(r *http.Request) (AuthRequest, error)

ReadAuthRequest reads socket_id and channel_name from a form-encoded (the pusher-js default) or JSON request body.

type AuthorizeFunc

type AuthorizeFunc func(r *http.Request, channel string) (ok bool, member *Member)

AuthorizeFunc decides whether the user behind r may subscribe to channel. For presence- channels it also returns the member to show; for private- channels the member is ignored and may be nil.

type BatchEvent

type BatchEvent struct {
	Channel  string
	Name     string
	Data     any
	SocketID string
}

BatchEvent is one event of TriggerBatch.

type ChannelAuth

type ChannelAuth struct {
	Auth        string `json:"auth"`
	ChannelData string `json:"channel_data,omitempty"`
}

ChannelAuth is the JSON answer to a channel authorization request.

type ChannelInfo

type ChannelInfo struct {
	Occupied          bool `json:"occupied"`
	UserCount         int  `json:"user_count,omitempty"`
	SubscriptionCount int  `json:"subscription_count,omitempty"`
}

ChannelInfo describes an occupied channel. UserCount (presence channels) and SubscriptionCount are only filled when asked for with info.

type ChatMember

type ChatMember struct {
	UserID  string `json:"user_id"`
	ReadSeq int64  `json:"read_seq"`
	Role    string `json:"role,omitempty"`
}

ChatMember is a member of a conversation.

type ChatToken

type ChatToken struct {
	Token     string    `json:"token"`
	ExpiresAt time.Time `json:"expires_at"`
}

ChatToken is a token for the Chat API client routes.

type Client

type Client struct {
	AppID  string
	Key    string
	Secret string
	// Host is the API base URL, such as https://ws.hibira.io (the default) or
	// the host shown on your app page. A bare host name means https.
	Host string

	// PushInstanceID and PushSecretKey turn on the push methods.
	PushInstanceID string
	PushSecretKey  string
	// PushEndpoint defaults to Host.
	PushEndpoint string

	// HTTPClient defaults to http.DefaultClient.
	HTTPClient *http.Client
	// Timeout of each call, default DefaultTimeout.
	Timeout time.Duration
	// Now defaults to time.Now.
	Now func() time.Time
}

Client calls the Hibira HTTP API for one app. The zero value is not usable: set AppID, Key and Secret, or use FromEnv.

func FromEnv

func FromEnv() *Client

FromEnv reads the settings from the environment: HIBIRA_APP_ID, HIBIRA_APP_KEY, HIBIRA_APP_SECRET, HIBIRA_HOST (with HIBIRA_PORT and HIBIRA_USE_TLS), HIBIRA_PUSH_INSTANCE_ID, HIBIRA_PUSH_SECRET_KEY and HIBIRA_PUSH_ENDPOINT.

func (*Client) AddMembers

func (c *Client) AddMembers(ctx context.Context, id string, userIDs ...string) (*Conversation, error)

AddMembers adds members to a conversation.

func (*Client) Approvals

func (c *Client) Approvals() *approvals.Client

Approvals returns an Approvals client for the same app; see package approvals.

func (*Client) AuthAnswer

func (c *Client) AuthAnswer(a AuthRequest, ok bool, member *Member) (int, any)

AuthAnswer is the status and JSON body that answer a channel authorization request, given the app's decision. Framework adapters use it.

func (*Client) AuthHandler

func (c *Client) AuthHandler(fn AuthorizeFunc) http.Handler

AuthHandler answers pusher-js channel authorization requests (channelAuthorization.endpoint) for private- and presence- channels. fn decides who may subscribe; a refusal answers 403.

http.Handle("POST /hibira/auth", client.AuthHandler(func(r *http.Request, ch string) (bool, *hibira.Member) {
	u := currentUser(r)
	if u == nil { return false, nil }
	if ch == "private-user-"+u.ID { return true, nil }
	if strings.HasPrefix(ch, "presence-room-") { return true, &hibira.Member{UserID: u.ID, UserInfo: map[string]string{"name": u.Name}} }
	return false, nil
}))
Example
package main

import (
	"log"
	"net/http"
	"strings"

	hibira "github.com/hibira-io/go"
)

func main() {
	client := hibira.FromEnv()
	currentUserID := func(r *http.Request) string { return r.Header.Get("X-User") } // your session lookup

	mux := http.NewServeMux()
	mux.Handle("/hibira/auth", client.AuthHandler(func(r *http.Request, channel string) (bool, *hibira.Member) {
		id := currentUserID(r)
		switch {
		case id == "":
			return false, nil
		case channel == "private-user-"+id:
			return true, nil
		case strings.HasPrefix(channel, "presence-room-"):
			return true, &hibira.Member{UserID: id, UserInfo: map[string]string{"name": "Ann"}}
		}
		return false, nil
	}))
	mux.Handle("/hibira/user-auth", client.UserAuthHandler(func(r *http.Request) *hibira.User {
		if id := currentUserID(r); id != "" {
			return &hibira.User{ID: id}
		}
		return nil
	}))
	mux.Handle("/hibira/webhook", client.WebhookHandler(func(r *http.Request, hook *hibira.Webhook) error {
		for _, e := range hook.Events {
			log.Println(e.Name, e.Channel)
		}
		return nil
	}))
}

func (*Client) AuthenticateUser

func (c *Client) AuthenticateUser(socketID string, user User) (*UserAuth, error)

AuthenticateUser signs a connection's user sign-in. It makes no network call.

func (*Client) AuthorizeChannel

func (c *Client) AuthorizeChannel(channel, socketID string, member *Member) (*ChannelAuth, error)

AuthorizeChannel signs a private- or presence- channel subscription for socketID. Presence channels need member. It makes no network call.

func (*Client) Channel

func (c *Client) Channel(ctx context.Context, channel string, info ...string) (*ChannelInfo, error)

Channel reads one channel. info may hold "user_count" and "subscription_count".

func (*Client) Channels

func (c *Client) Channels(ctx context.Context, prefix string, info ...string) (map[string]ChannelInfo, error)

Channels lists the occupied channels whose names start with prefix (all when empty). info may be "user_count" (presence- prefixes only).

func (*Client) ChatRequest

func (c *Client) ChatRequest(ctx context.Context, method, path string, query url.Values, body any, out any) error

ChatRequest makes any Chat API call, signed: path is relative to /apps/APP_ID/chat, such as /conversations/ID/typing. out, when not nil, receives the JSON answer.

func (*Client) DeleteConversation

func (c *Client) DeleteConversation(ctx context.Context, id string) error

DeleteConversation deletes a conversation with its members, messages and files.

func (*Client) DeletePushUser

func (c *Client) DeletePushUser(ctx context.Context, userID string) error

DeletePushUser removes a user and their devices from push.

func (*Client) GetConversation

func (c *Client) GetConversation(ctx context.Context, id string) (*Conversation, error)

GetConversation reads a conversation.

func (*Client) ListMessages

func (c *Client) ListMessages(ctx context.Context, id string, o ListOptions) (*MessagePage, error)

ListMessages reads messages, oldest first.

func (*Client) MarkRead

func (c *Client) MarkRead(ctx context.Context, id, userID string, seq int64) (int64, error)

MarkRead moves how far userID has read to seq and returns the new read_seq.

func (*Client) NewChatToken

func (c *Client) NewChatToken(ctx context.Context, userID, conversationID string, join bool, ttl time.Duration) (*ChatToken, error)

NewChatToken makes a token for the Chat API client routes. conversationID limits it to one conversation (join lets the user add themselves); ttl is 60 seconds to 24 hours, default 1 hour.

func (*Client) Publish

func (c *Client) Publish(ctx context.Context, e Event) error

Publish publishes an event to up to 100 channels.

func (*Client) PushToInterests

func (c *Client) PushToInterests(ctx context.Context, interests []string, body map[string]any) (*PushResult, error)

PushToInterests sends a push notification to the devices subscribed to any of interests. body is a Beams publish body:

map[string]any{
	"web":  map[string]any{"notification": map[string]any{"title": "New post", "deep_link": "https://example.com/p/1"}},
	"fcm":  map[string]any{"notification": map[string]any{"title": "New post"}},
	"apns": map[string]any{"aps": map[string]any{"alert": map[string]any{"title": "New post"}}},
}

func (*Client) PushToUsers

func (c *Client) PushToUsers(ctx context.Context, userIDs []string, body map[string]any) (*PushResult, error)

PushToUsers sends a push notification to the devices of up to 1000 users.

func (*Client) PushToken

func (c *Client) PushToken(userID string, ttl time.Duration) (string, error)

PushToken is a push user token for setUserId in the web, Android and iOS SDKs. ttl defaults to 24 hours. It makes no network call.

func (*Client) PutConversation

func (c *Client) PutConversation(ctx context.Context, id string, in ConversationInput) (*Conversation, error)

PutConversation creates or replaces a conversation.

func (*Client) RemoveMember

func (c *Client) RemoveMember(ctx context.Context, id, userID string) (*Conversation, error)

RemoveMember removes a member from a conversation.

func (*Client) SendMessage

func (c *Client) SendMessage(ctx context.Context, id string, in MessageInput) (*SentMessage, error)

SendMessage posts a message as a member.

Example
package main

import (
	"context"

	hibira "github.com/hibira-io/go"
)

func main() {
	client := hibira.FromEnv()
	ctx := context.Background()
	_, _ = client.PutConversation(ctx, "order-1042", hibira.ConversationInput{Name: "Order #1042", Members: []string{"cust_7", "agent_2"}})
	_, _ = client.SendMessage(ctx, "order-1042", hibira.MessageInput{UserID: "agent_2", Text: "Your parcel left the warehouse.", Push: "offline"})
}

func (*Client) SystemMessage

func (c *Client) SystemMessage(ctx context.Context, id, text string, metadata any) (*Message, error)

SystemMessage posts a system message (joined, transferred, closed): never pushed, never unread.

func (*Client) TerminateUserConnections

func (c *Client) TerminateUserConnections(ctx context.Context, userID string) error

TerminateUserConnections disconnects every connection signed in as userID.

func (*Client) Trigger

func (c *Client) Trigger(ctx context.Context, channel, event string, data any) error

Trigger publishes an event to one channel. Data that is not a string is sent as JSON.

func (*Client) TriggerBatch

func (c *Client) TriggerBatch(ctx context.Context, events []BatchEvent) error

TriggerBatch publishes several events in one request (10 at most by default).

func (*Client) Typing

func (c *Client) Typing(ctx context.Context, id, userID string, typing bool) error

Typing tells the other members that userID is typing, or stopped.

func (*Client) UserAuthAnswer

func (c *Client) UserAuthAnswer(a AuthRequest, user *User) (int, any)

UserAuthAnswer is the status and JSON body that answer a user sign-in request for user (nil refuses it). Framework adapters use it.

func (*Client) UserAuthHandler

func (c *Client) UserAuthHandler(fn func(r *http.Request) *User) http.Handler

UserAuthHandler answers pusher-js user sign-in requests (userAuthentication.endpoint). fn returns the signed-in user, or nil to answer 403.

func (*Client) UserConversations

func (c *Client) UserConversations(ctx context.Context, userID string, limit int, before string) (*ConversationPage, error)

UserConversations lists a user's conversations, latest activity first, each with its unread count. before is a previous page's Next.

func (*Client) Users

func (c *Client) Users(ctx context.Context, channel string) ([]string, error)

Users lists the user IDs subscribed to a presence channel.

func (*Client) VerifyWebhook

func (c *Client) VerifyWebhook(key, signature string, body []byte) (*Webhook, error)

VerifyWebhook checks a webhook's X-Pusher-Key and X-Pusher-Signature headers against the raw body and returns the parsed delivery. It returns an error wrapping ErrInvalidWebhook when they do not match.

func (*Client) WebhookHandler

func (c *Client) WebhookHandler(fn func(r *http.Request, hook *Webhook) error) http.Handler

WebhookHandler verifies webhook deliveries and passes them to fn. A forged delivery gets 401; an error from fn answers 500 so Hibira retries.

type Conversation

type Conversation struct {
	ID        string          `json:"id"`
	Name      string          `json:"name,omitempty"`
	Metadata  json.RawMessage `json:"metadata,omitempty"`
	Members   []ChatMember    `json:"members,omitempty"`
	Watchers  []string        `json:"watchers,omitempty"`
	LastSeq   int64           `json:"last_seq"`
	Unread    int64           `json:"unread,omitempty"`
	CreatedAt *time.Time      `json:"created_at,omitempty"`
	UpdatedAt *time.Time      `json:"updated_at,omitempty"`
}

Conversation is a Chat API conversation.

type ConversationInput

type ConversationInput struct {
	Name     string            `json:"name,omitempty"`
	Metadata any               `json:"metadata,omitempty"`
	Members  []string          `json:"members,omitempty"`
	Roles    map[string]string `json:"roles,omitempty"`
	Watchers []string          `json:"watchers,omitempty"`
}

ConversationInput creates or replaces a conversation. Members and Watchers left nil keep the current ones.

type ConversationPage

type ConversationPage struct {
	Conversations []Conversation `json:"conversations"`
	// Next goes in Before for the following page; empty on the last one.
	Next string `json:"next,omitempty"`
}

ConversationPage is a user's conversations, latest activity first.

type Error

type Error struct {
	Status  int
	Message string
	Body    []byte
}

Error is an answer from the Hibira API other than 2xx.

func (*Error) Error

func (e *Error) Error() string

type Event

type Event struct {
	// Channels are 1 to 100 channel names.
	Channels []string
	// Name is the event name, 1 to 200 characters.
	Name string
	// Data is sent as is when it is a string or []byte, otherwise as JSON.
	Data any
	// SocketID, when set, leaves out that connection (the sender's own tab).
	SocketID string
}

Event is one event to publish.

type ListOptions

type ListOptions struct {
	After int64
	Limit int
	Last  int
}

ListOptions picks messages: After a seq (with Limit), or the Last n.

type Member

type Member struct {
	UserID string `json:"user_id"`
	// UserInfo is shown to the other members, such as {"name": "Ann"}.
	UserInfo any `json:"user_info,omitempty"`
}

Member is the user in a presence channel.

type Message

type Message struct {
	ID        string              `json:"id"`
	Seq       int64               `json:"seq"`
	Sender    string              `json:"sender,omitempty"`
	Name      string              `json:"name,omitempty"`
	Kind      string              `json:"kind"` // text or system
	Text      string              `json:"text,omitempty"`
	Metadata  json.RawMessage     `json:"metadata,omitempty"`
	VisibleTo []string            `json:"visible_to,omitempty"`
	Reactions map[string][]string `json:"reactions,omitempty"`
	CreatedAt *time.Time          `json:"created_at,omitempty"`
	EditedAt  *time.Time          `json:"edited_at,omitempty"`
	DeletedAt *time.Time          `json:"deleted_at,omitempty"`
}

Message is a Chat API message.

type MessageInput

type MessageInput struct {
	// UserID is the sending member. Required.
	UserID   string `json:"user_id"`
	Name     string `json:"name,omitempty"`
	Text     string `json:"text,omitempty"`
	Metadata any    `json:"metadata,omitempty"`
	// Push is "offline" (default), "always" or "never".
	Push      string   `json:"push,omitempty"`
	PushTitle string   `json:"push_title,omitempty"`
	PushURL   string   `json:"push_url,omitempty"`
	VisibleTo []string `json:"visible_to,omitempty"`
	// IdempotencyKey makes a retry return the stored message instead of a new one.
	IdempotencyKey string `json:"idempotency_key,omitempty"`
}

MessageInput is a message sent on a member's behalf.

type MessagePage

type MessagePage struct {
	Messages []Message `json:"messages"`
	LastSeq  int64     `json:"last_seq"`
}

MessagePage is a page of messages, oldest first.

type PushResult

type PushResult struct {
	PublishID string `json:"publishId"`
}

PushResult is the answer to a push publish.

type SentMessage

type SentMessage struct {
	Message   Message         `json:"message"`
	Duplicate bool            `json:"duplicate,omitempty"`
	Push      json.RawMessage `json:"push,omitempty"`
}

SentMessage is the answer to SendMessage.

type User

type User struct {
	ID        string   `json:"id"`
	UserInfo  any      `json:"user_info,omitempty"`
	Watchlist []string `json:"watchlist,omitempty"`
}

User is the user of a connection's sign-in (pusher.signin()), which the Chat API and server-to-user events need.

type UserAuth

type UserAuth struct {
	Auth     string `json:"auth"`
	UserData string `json:"user_data"`
}

UserAuth is the JSON answer to a user sign-in request.

type Webhook

type Webhook struct {
	TimeMs int64          `json:"time_ms"`
	Events []WebhookEvent `json:"events"`
	// Raw is the whole body, for fields this struct does not name.
	Raw json.RawMessage `json:"-"`
}

Webhook is a verified webhook delivery.

type WebhookEvent

type WebhookEvent struct {
	Name     string `json:"name"`
	Channel  string `json:"channel,omitempty"`
	Event    string `json:"event,omitempty"`
	Data     string `json:"data,omitempty"`
	SocketID string `json:"socket_id,omitempty"`
	UserID   string `json:"user_id,omitempty"`
	// Raw is the whole event.
	Raw json.RawMessage `json:"-"`
}

WebhookEvent is one event of a webhook: channel_occupied, channel_vacated, member_added, member_removed, client_event, subscription_count, cache_miss, chat_message and others.

func (*WebhookEvent) UnmarshalJSON

func (e *WebhookEvent) UnmarshalJSON(b []byte) error

UnmarshalJSON keeps the raw event next to the named fields.

Directories

Path Synopsis
Package approvals asks a person for a decision from a Go server, job or agent with Hibira Approvals (https://hibira.io/approvals), and reads the answer.
Package approvals asks a person for a decision from a Go server, job or agent with Hibira Approvals (https://hibira.io/approvals), and reads the answer.
Package livechat holds server helpers for Hibira Live Chat (https://chat.hibira.io).
Package livechat holds server helpers for Hibira Live Chat (https://chat.hibira.io).
Package stream sends an LLM's output (or any text produced bit by bit) to a Hibira channel as it is written.
Package stream sends an LLM's output (or any text produced bit by bit) to a Hibira channel as it is written.
Package waitingroom checks Hibira waiting room passes in Go and puts a net/http middleware in front of the pages a room protects.
Package waitingroom checks Hibira waiting room passes in Go and puts a net/http middleware in front of the pages a room protects.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL