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)
}
}
Output:
Index ¶
- Constants
- Variables
- func StatusOf(err error) int
- func WriteJSON(w http.ResponseWriter, status int, v any)
- type AuthRequest
- type AuthorizeFunc
- type BatchEvent
- type ChannelAuth
- type ChannelInfo
- type ChatMember
- type ChatToken
- type Client
- func (c *Client) AddMembers(ctx context.Context, id string, userIDs ...string) (*Conversation, error)
- func (c *Client) Approvals() *approvals.Client
- func (c *Client) AuthAnswer(a AuthRequest, ok bool, member *Member) (int, any)
- func (c *Client) AuthHandler(fn AuthorizeFunc) http.Handler
- func (c *Client) AuthenticateUser(socketID string, user User) (*UserAuth, error)
- func (c *Client) AuthorizeChannel(channel, socketID string, member *Member) (*ChannelAuth, error)
- func (c *Client) Channel(ctx context.Context, channel string, info ...string) (*ChannelInfo, error)
- func (c *Client) Channels(ctx context.Context, prefix string, info ...string) (map[string]ChannelInfo, error)
- func (c *Client) ChatRequest(ctx context.Context, method, path string, query url.Values, body any, out any) error
- func (c *Client) DeleteConversation(ctx context.Context, id string) error
- func (c *Client) DeletePushUser(ctx context.Context, userID string) error
- func (c *Client) GetConversation(ctx context.Context, id string) (*Conversation, error)
- func (c *Client) ListMessages(ctx context.Context, id string, o ListOptions) (*MessagePage, error)
- func (c *Client) MarkRead(ctx context.Context, id, userID string, seq int64) (int64, error)
- func (c *Client) NewChatToken(ctx context.Context, userID, conversationID string, join bool, ...) (*ChatToken, error)
- func (c *Client) Publish(ctx context.Context, e Event) error
- func (c *Client) PushToInterests(ctx context.Context, interests []string, body map[string]any) (*PushResult, error)
- func (c *Client) PushToUsers(ctx context.Context, userIDs []string, body map[string]any) (*PushResult, error)
- func (c *Client) PushToken(userID string, ttl time.Duration) (string, error)
- func (c *Client) PutConversation(ctx context.Context, id string, in ConversationInput) (*Conversation, error)
- func (c *Client) RemoveMember(ctx context.Context, id, userID string) (*Conversation, error)
- func (c *Client) SendMessage(ctx context.Context, id string, in MessageInput) (*SentMessage, error)
- func (c *Client) SystemMessage(ctx context.Context, id, text string, metadata any) (*Message, error)
- func (c *Client) TerminateUserConnections(ctx context.Context, userID string) error
- func (c *Client) Trigger(ctx context.Context, channel, event string, data any) error
- func (c *Client) TriggerBatch(ctx context.Context, events []BatchEvent) error
- func (c *Client) Typing(ctx context.Context, id, userID string, typing bool) error
- func (c *Client) UserAuthAnswer(a AuthRequest, user *User) (int, any)
- func (c *Client) UserAuthHandler(fn func(r *http.Request) *User) http.Handler
- func (c *Client) UserConversations(ctx context.Context, userID string, limit int, before string) (*ConversationPage, error)
- func (c *Client) Users(ctx context.Context, channel string) ([]string, error)
- func (c *Client) VerifyWebhook(key, signature string, body []byte) (*Webhook, error)
- func (c *Client) WebhookHandler(fn func(r *http.Request, hook *Webhook) error) http.Handler
- type Conversation
- type ConversationInput
- type ConversationPage
- type Error
- type Event
- type ListOptions
- type Member
- type Message
- type MessageInput
- type MessagePage
- type PushResult
- type SentMessage
- type User
- type UserAuth
- type Webhook
- type WebhookEvent
Examples ¶
Constants ¶
const DefaultHost = "https://ws.hibira.io"
DefaultHost serves the Hibira HTTP API.
const DefaultTimeout = 10 * time.Second
DefaultTimeout is how long one API call may take unless Client.Timeout says otherwise.
const MaxTriggerChannels = 100
MaxTriggerChannels is how many channels one event may go to.
const MaxWebhookBody = 1 << 20
MaxWebhookBody is the largest webhook body the handlers read.
Variables ¶
var ErrConfig = errors.New("hibira: missing setting")
ErrConfig is returned when a setting the call needs is missing.
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 ¶
Types ¶
type AuthRequest ¶
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 ¶
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 ¶
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 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 ¶
Approvals returns an Approvals client for the same app; see package approvals.
func (*Client) AuthAnswer ¶
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
}))
}
Output:
func (*Client) AuthenticateUser ¶
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 ¶
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 ¶
DeleteConversation deletes a conversation with its members, messages and files.
func (*Client) DeletePushUser ¶
DeletePushUser removes a user and their devices from push.
func (*Client) GetConversation ¶
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 ¶
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) 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 ¶
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 ¶
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"})
}
Output:
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 ¶
TerminateUserConnections disconnects every connection signed in as userID.
func (*Client) Trigger ¶
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) 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 ¶
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) VerifyWebhook ¶
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.
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 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 ¶
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 ¶
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 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. |