Documentation ¶
Overview ¶
Package pusher is the Golang library for interacting with the Pusher HTTP API.
This package lets you trigger events to your client and query the state of your Pusher channels. When used with a server, you can validate Pusher webhooks and authenticate private- or presence-channels.
In order to use this library, you need to have a free account on http://pusher.com. After registering, you will need the application credentials for your app.
Getting Started ¶
To create a new client, pass in your application credentials to a `pusher.Client` struct:
pusherClient := pusher.Client{ AppID: "your_app_id", Key: "your_app_key", Secret: "your_app_secret", }
To start triggering events on a channel, we call `pusherClient.Trigger`:
data := map[string]string{"message": "hello world"} // trigger an event on a channel, along with a data payload pusherClient.Trigger("test_channel", "event", data)
Read on to see what more you can do with this library, such as authenticating private- and presence-channels, validating Pusher webhooks, and querying the HTTP API to get information about your channels.
Author: Jamie Patel, Pusher
Index ¶
- type Channel
- type ChannelListItem
- type ChannelParams
- type ChannelsList
- type ChannelsParams
- type Client
- func (c *Client) AuthenticatePresenceChannel(params []byte, member MemberData) (response []byte, err error)deprecated
- func (c *Client) AuthenticatePrivateChannel(params []byte) (response []byte, err error)deprecated
- func (c *Client) AuthenticateUser(params []byte, userData map[string]interface{}) (response []byte, err error)
- func (c *Client) AuthorizePresenceChannel(params []byte, member MemberData) (response []byte, err error)
- func (c *Client) AuthorizePrivateChannel(params []byte) (response []byte, err error)
- func (c *Client) Channel(name string, params ChannelParams) (*Channel, error)
- func (c *Client) Channels(params ChannelsParams) (*ChannelsList, error)
- func (c *Client) GetChannelUsers(name string) (*Users, error)
- func (c *Client) SendToUser(userId string, eventName string, data interface{}) error
- func (c *Client) Trigger(channel string, eventName string, data interface{}) error
- func (c *Client) TriggerBatch(batch []Event) (*TriggerBatchChannelsList, error)
- func (c *Client) TriggerExclusive(channel string, eventName string, data interface{}, socketID string) errordeprecated
- func (c *Client) TriggerMulti(channels []string, eventName string, data interface{}) error
- func (c *Client) TriggerMultiExclusive(channels []string, eventName string, data interface{}, socketID string) errordeprecated
- func (c *Client) TriggerMultiWithParams(channels []string, eventName string, data interface{}, params TriggerParams) (*TriggerChannelsList, error)
- func (c *Client) TriggerWithParams(channel string, eventName string, data interface{}, params TriggerParams) (*TriggerChannelsList, error)
- func (c *Client) Webhook(header http.Header, body []byte) (*Webhook, error)
- type EncryptedMessage
- type Event
- type MemberData
- type TriggerBatchChannelListItem
- type TriggerBatchChannelsList
- type TriggerChannelListItem
- type TriggerChannelsList
- type TriggerParams
- type User
- type Users
- type Webhook
- type WebhookEvent
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Channel ¶
type Channel struct { Name string Occupied bool `json:"occupied,omitempty"` UserCount int `json:"user_count,omitempty"` SubscriptionCount int `json:"subscription_count,omitempty"` }
Channel represents the information about a channel from the Pusher API.
type ChannelListItem ¶
type ChannelListItem struct {
UserCount int `json:"user_count"`
}
ChannelListItem represents an item within ChannelsList
type ChannelParams ¶
type ChannelParams struct { // Info is comma-separated vales of `"user_count"`, for // presence-channels, and `"subscription_count"`, for all-channels. // Note that the subscription count is not allowed by default. Please // contact us at http://support.pusher.com if you wish to enable this. // Pass in `nil` if you do not wish to specify any query attributes. Info *string }
ChannelParams are any parameters than can be sent with a Channel request.
type ChannelsList ¶
type ChannelsList struct {
Channels map[string]ChannelListItem `json:"channels"`
}
ChannelsList represents a list of channels received by the Pusher API.
type ChannelsParams ¶
type ChannelsParams struct { // FilterByPrefix will filter the returned channels. FilterByPrefix *string // Info should be specified with a value of "user_count" to get number // of users subscribed to a presence-channel. Pass in `nil` if you do // not wish to specify any query attributes. Info *string }
ChannelsParams are any parameters than can be sent with a Channels request.
type Client ¶
type Client struct { AppID string Key string Secret string Host string // host or host:port pair Secure bool // true for HTTPS Cluster string HTTPClient *http.Client EncryptionMasterKey string // deprecated EncryptionMasterKeyBase64 string // for E2E OverrideMaxMessagePayloadKB int // set the agreed Pusher message limit increase // contains filtered or unexported fields }
Client to the HTTP API of Pusher.
There easiest way to configure the library is by creating a `Pusher` instance:
client := pusher.Client{ AppID: "your_app_id", Key: "your_app_key", Secret: "your_app_secret", }
To ensure requests occur over HTTPS, set the `Secure` property of a `pusher.Client` to `true`.
client.Secure = true // false by default
If you wish to set a time-limit for each HTTP request, set the `Timeout` property to an instance of `time.Duration`, for example:
client.Timeout = time.Second * 3 // 5 seconds by default
Changing the `pusher.Client`'s `Host` property will make sure requests are sent to your specified host.
client.Host = "foo.bar.com" // by default this is "api.pusherapp.com".
func ClientFromEnv ¶
ClientFromEnv allows instantiation of a client from an environment variable. This is particularly relevant if you are using Pusher as a Heroku add-on, which stores credentials in a `"PUSHER_URL"` environment variable. For example:
client := pusher.ClientFromEnv("PUSHER_URL")
func ClientFromURL ¶
ClientFromURL allows client instantiation from a specially-crafted Pusher URL.
c := pusher.ClientFromURL("http://key:secret@api.pusherapp.com/apps/app_id")
func (*Client) AuthenticatePresenceChannel
deprecated
func (c *Client) AuthenticatePresenceChannel(params []byte, member MemberData) (response []byte, err error)
AuthenticatePresenceChannel allows you to authorize a users subscription to a presence channel. It returns an authorization signature to send back to the client and authorize them. In order to identify a user, clients are sent a user_id and, optionally, custom data.
Deprecated: use AuthorizePresenceChannel instead.
func (*Client) AuthenticatePrivateChannel
deprecated
AuthenticatePrivateChannel allows you to authorize a users subscription to a private channel. It returns an authorization signature to send back to the client and authorize them.
Deprecated: use AuthorizePrivateChannel instead.
func (*Client) AuthenticateUser ¶ added in v5.1.0
func (c *Client) AuthenticateUser(params []byte, userData map[string]interface{}) (response []byte, err error)
AuthenticateUser allows you to authenticate a user's connection. It returns an authentication signature to send back to the client and authenticate them. In order to identify a user, this method acceps a map containing arbitrary user data. It must contain at least an id field with the user's id as a string.
For more information see our docs: http://pusher.com/docs/authenticating_users.
This is an example of authenticating a user, using the built-in Golang HTTP library to start a server.
In order to authenticate a client, one must read the response into type `[]byte` and pass it in. This will return a signature in the form of a `[]byte` for you to send back to the client.
func pusherUserAuth(res http.ResponseWriter, req *http.Request) { params, _ := ioutil.ReadAll(req.Body) userData := map[string]interface{} { "id": "1234", "twitter": "jamiepatel" } response, err := client.AuthenticateUser(params, userData) if err != nil { panic(err) } fmt.Fprintf(res, string(response)) } func main() { http.HandleFunc("/pusher/user-auth", pusherUserAuth) http.ListenAndServe(":5000", nil) }
func (*Client) AuthorizePresenceChannel ¶ added in v5.1.0
func (c *Client) AuthorizePresenceChannel(params []byte, member MemberData) (response []byte, err error)
AuthorizePresenceChannel allows you to authorize a users subscription to a presence channel. It returns an authorization signature to send back to the client and authorize them. In order to identify a user, clients are sent a user_id and, optionally, custom data.
In this library, one does this by passing a `pusher.MemberData` instance.
params, _ := ioutil.ReadAll(req.Body) presenceData := pusher.MemberData{ UserID: "1", UserInfo: map[string]string{ "twitter": "jamiepatel", }, } response, err := client.AuthorizePresenceChannel(params, presenceData) if err != nil { panic(err) } fmt.Fprintf(res, response)
func (*Client) AuthorizePrivateChannel ¶ added in v5.1.0
AuthorizePrivateChannel allows you to authorize a users subscription to a private channel. It returns an authorization signature to send back to the client and authorize them.
For more information see our docs: http://pusher.com/docs/authorizing_users.
This is an example of authorizing a private-channel, using the built-in Golang HTTP library to start a server.
In order to authorize a client, one must read the response into type `[]byte` and pass it in. This will return a signature in the form of a `[]byte` for you to send back to the client.
func pusherAuth(res http.ResponseWriter, req *http.Request) { params, _ := ioutil.ReadAll(req.Body) response, err := client.AuthorizePrivateChannel(params) if err != nil { panic(err) } fmt.Fprintf(res, string(response)) } func main() { http.HandleFunc("/pusher/auth", pusherAuth) http.ListenAndServe(":5000", nil) }
func (*Client) Channel ¶
func (c *Client) Channel(name string, params ChannelParams) (*Channel, error)
Channel allows you to get the state of a single channel.
attributes := "user_count,subscription_count" params := pusher.ChannelParams{Info: &attributes} channel, err := client.Channel("presence-chatroom", params) //channel=> &{Name:presence-chatroom Occupied:true UserCount:42 SubscriptionCount:42}
func (*Client) Channels ¶
func (c *Client) Channels(params ChannelsParams) (*ChannelsList, error)
Channels returns a list of all the channels in an application.
prefixFilter := "presence-" attributes := "user_count" params := pusher.ChannelsParams{FilterByPrefix: &prefixFilter, Info: &attributes} channels, err := client.Channels(params) //channels=> &{Channels:map[presence-chatroom:{UserCount:4} presence-notifications:{UserCount:31} ]}
func (*Client) GetChannelUsers ¶
GetChannelUsers returns a list of users in a presence-channel by passing to this method the channel name.
users, err := client.GetChannelUsers("presence-chatroom") //users=> &{List:[{ID:13} {ID:90}]}
func (*Client) SendToUser ¶ added in v5.1.0
SendToUser triggers an event to a specific user. Pass in the user id, the event's name, and a data payload. The data payload must be marshallable into JSON.
data := map[string]string{"hello": "world"} client.SendToUser("user123", "say_hello", data)
func (*Client) Trigger ¶
Trigger triggers an event to the Pusher API. It is possible to trigger an event on one or more channels. Channel names can contain only characters which are alphanumeric, `_` or `-“ and have to be at most 200 characters long. Event name can be at most 200 characters long too.
Pass in the channel's name, the event's name, and a data payload. The data payload must be marshallable into JSON.
data := map[string]string{"hello": "world"} client.Trigger("greeting_channel", "say_hello", data)
func (*Client) TriggerBatch ¶
func (c *Client) TriggerBatch(batch []Event) (*TriggerBatchChannelsList, error)
TriggerBatch triggers multiple events on multiple channels in a single call:
info := "subscription_count" socketID := "1234.12" client.TriggerBatch([]pusher.Event{ { Channel: "donut-1", Name: "ev1", Data: "d1", SocketID: socketID, Info: &info }, { Channel: "private-encrypted-secretdonut", Name: "ev2", Data: "d2", SocketID: socketID, Info: &info }, })
func (*Client) TriggerExclusive
deprecated
func (c *Client) TriggerExclusive(channel string, eventName string, data interface{}, socketID string) error
TriggerExclusive triggers an event excluding a recipient whose connection has the `socket_id` you specify here from receiving the event. You can read more here: http://pusher.com/docs/duplicates.
client.TriggerExclusive("a_channel", "event", data, "123.12")
Deprecated: use TriggerWithParams instead.
func (*Client) TriggerMulti ¶
TriggerMulti is the same as `client.Trigger`, except one passes in a slice of `channels` as the first parameter. The maximum length of channels is 100.
client.TriggerMulti([]string{"a_channel", "another_channel"}, "event", data)
func (*Client) TriggerMultiExclusive
deprecated
func (c *Client) TriggerMultiExclusive(channels []string, eventName string, data interface{}, socketID string) error
TriggerMultiExclusive triggers an event to multiple channels excluding a recipient whose connection has the `socket_id` you specify here from receiving the event on any of the channels.
client.TriggerMultiExclusive([]string{"a_channel", "another_channel"}, "event", data, "123.12")
Deprecated: use TriggerMultiWithParams instead.
func (*Client) TriggerMultiWithParams ¶
func (c *Client) TriggerMultiWithParams( channels []string, eventName string, data interface{}, params TriggerParams, ) (*TriggerChannelsList, error)
TriggerMultiWithParams is the same as `client.TriggerMulti`, except it allows additional parameters to be specified in the same way as `client.TriggerWithParams`.
func (*Client) TriggerWithParams ¶
func (c *Client) TriggerWithParams( channel string, eventName string, data interface{}, params TriggerParams, ) (*TriggerChannelsList, error)
TriggerWithParams is the same as `client.Trigger`, except it allows additional parameters to be passed in. See: https://pusher.com/docs/channels/library_auth_reference/rest-api#request for a complete list.
data := map[string]string{"hello": "world"} socketID := "1234.12" attributes := "user_count" params := pusher.TriggerParams{SocketID: &socketID, Info: &attributes} channels, err := client.Trigger("greeting_channel", "say_hello", data, params) //channels=> &{Channels:map[presence-chatroom:{UserCount:4} presence-notifications:{UserCount:31}]}
func (*Client) Webhook ¶
Webhook allows you to check that a Webhook you receive is indeed from Pusher, by checking the token and authentication signature in the header of the request. On your dashboard at http://app.pusher.com, you can set up webhooks to POST a payload to your server after certain events. Such events include channels being occupied or vacated, members being added or removed in presence-channels, or after client-originated events. For more information see https://pusher.com/docs/webhooks.
If the webhook is valid, a `*pusher.Webhook* will be returned, and the `err` value will be nil. If it is invalid, the first return value will be nil, and an error will be passed.
func pusherWebhook(res http.ResponseWriter, req *http.Request) { body, _ := ioutil.ReadAll(req.Body) webhook, err := client.Webhook(req.Header, body) if err != nil { fmt.Println("Webhook is invalid :(") } else { fmt.Printf("%+v\n", webhook.Events) } }
type EncryptedMessage ¶
EncryptedMessage contains an encrypted message
type Event ¶
type Event struct { Channel string Name string Data interface{} SocketID *string // Info is part of an [experimental feature](https://pusher.com/docs/lab#experimental-program). Info *string }
Event stores all the data for one Event that can be triggered.
type MemberData ¶
type MemberData struct { UserID string `json:"user_id"` UserInfo map[string]string `json:"user_info,omitempty"` }
MemberData represents what to assign to a channel member, consisting of a `UserID` and any custom `UserInfo`.
type TriggerBatchChannelsList ¶
type TriggerBatchChannelsList struct {
Batch []TriggerBatchChannelListItem `json:"batch"`
}
type TriggerChannelListItem ¶
type TriggerChannelsList ¶
type TriggerChannelsList struct {
Channels map[string]TriggerChannelListItem `json:"channels"`
}
type TriggerParams ¶
type TriggerParams struct { // SocketID excludes a recipient whose connection has the `socket_id` // specified here. You can read more here: // http://pusher.com/docs/duplicates. SocketID *string // Info is comma-separated vales of `"user_count"`, for // presence-channels, and `"subscription_count"`, for all-channels. // Note that the subscription count is not allowed by default. Please // contact us at http://support.pusher.com if you wish to enable this. // Pass in `nil` if you do not wish to specify any query attributes. // This is part of an [experimental feature](https://pusher.com/docs/lab#experimental-program). Info *string }
ChannelsParams are any parameters than can be sent with a TriggerWithParams or TriggerMultiWithParams requests.
type User ¶
type User struct {
ID string `json:"id"`
}
User represents a user and contains their ID.
type Users ¶
type Users struct {
List []User `json:"users"`
}
Users represents a list of users in a presence-channel
type Webhook ¶
type Webhook struct { TimeMs int `json:"time_ms"` // the timestamp of the request Events []WebhookEvent `json:"events"` // the events associated with the webhook }
Webhook is the parsed form of a valid webhook received by the server.
type WebhookEvent ¶
type WebhookEvent struct { Name string `json:"name"` // the type of the event Channel string `json:"channel"` // the channel on which it was sent Event string `json:"event,omitempty"` // the name of the event Data string `json:"data,omitempty"` // the data associated with the event SocketID string `json:"socket_id,omitempty"` // the socket_id of the sending socket UserID string `json:"user_id,omitempty"` // the user_id of a member who has joined or vacated a presence-channel }
WebhookEvent is the parsed form of a valid webhook event received by the server.