pusher-http-go: github.com/pusher/pusher-http-go Index | Files

package pusher

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

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, simply pass in your application credentials to a `pusher.Client` struct:

client := pusher.Client{
  AppId: "your_app_id",
  Key: "your_app_key",
  Secret: "your_app_secret",

To start triggering events on a channel, we simply call `client.Trigger`:

data := map[string]string{"message": "hello world"}

// trigger an event on a channel, along with a data payload
client.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


Package Files

client.go crypto.go doc.go event.go push_notifications.go request.go request_url.go response_parsing.go util.go webhook.go


const (
    PushNotifHostDefault       = "nativepush-cluster1.pusher.com"
    PushNotifAPIPrefixDefault  = "server_api"
    PushNotifAPIVersionDefault = "v1"

type BufferedEvents Uses

type BufferedEvents struct {
    EventIds map[string]string `json:"event_ids,omitempty"`

type Channel Uses

type Channel struct {
    Name              string
    Occupied          bool `json:"occupied,omitempty"`
    UserCount         int  `json:"user_count,omitempty"`
    SubscriptionCount int  `json:"subscription_count,omitempty"`

Represents the information received about a channel from the Pusher API.

type ChannelListItem Uses

type ChannelListItem struct {
    UserCount int `json:"user_count"`

An item of ChannelsList

type ChannelsList Uses

type ChannelsList struct {
    Channels map[string]ChannelListItem `json:"channels"`

Represents a list of channels received by the Pusher API.

type Client Uses

type Client struct {
    AppId                string
    Key                  string
    Secret               string
    Host                 string // host or host:port pair
    PushNotificationHost string
    Secure               bool // true for HTTPS
    Cluster              string
    HttpClient           *http.Client

Client to the HTTP API of Pusher.

There easiest way to configure the library is by creating a new `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 `Encrypted` 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 // set the timeout to 3 seconds - this is 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".

If you wish to use push notifications, you need to define the Client.PushNotificationHost, please see Pusher docs for more details: https://pusher.com/docs/push_notifications

func ClientFromEnv Uses

func ClientFromEnv(key string) (*Client, error)

Alternatively, you can instantiate 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 Uses

func ClientFromURL(url string) (*Client, error)

Clients can be instantiated from a specially-crafted Pusher URL. For example:

client := pusher.ClientFromURL("http://key:secret@api.pusherapp.com/apps/app_id")

func (*Client) AuthenticatePresenceChannel Uses

func (c *Client) AuthenticatePresenceChannel(params []byte, member MemberData) (response []byte, err error)

Using presence channels is similar to private channels, but 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.AuthenticatePresenceChannel(params, presenceData)

if err != nil {

fmt.Fprintf(res, response)

func (*Client) AuthenticatePrivateChannel Uses

func (c *Client) AuthenticatePrivateChannel(params []byte) (response []byte, err error)

Application security is very important so Pusher provides a mechanism for authenticating a user’s access to a channel at the point of subscription.

This can be used both to restrict access to private channels, and in the case of presence channels notify subscribers of who else is also subscribed via presence events.

This library provides a mechanism for generating an authentication signature to send back to the client and authorize them.

For more information see our docs: http://pusher.com/docs/authenticating_users.

This is an example of authenticating 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.AuthenticatePrivateChannel(params)

	if err != nil {

	fmt.Fprintf(res, string(response))


func main() {
	http.HandleFunc("/pusher/auth", pusherAuth)
	http.ListenAndServe(":5000", nil)

func (*Client) Channel Uses

func (c *Client) Channel(name string, additionalQueries map[string]string) (*Channel, error)

Get the state of a single channel.

The parameter `additionalQueries` is a map with query options. An `"info"` key can have 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.

channelParams := map[string]string{
	"info": "user_count,subscription_count",

channel, err := client.Channel("presence-chatroom", channelParams)

//channel=> &{Name:presence-chatroom Occupied:true UserCount:42 SubscriptionCount:42}

func (*Client) Channels Uses

func (c *Client) Channels(additionalQueries map[string]string) (*ChannelsList, error)

One can use this method to get a list of all the channels in an application.

The parameter `additionalQueries` is a map with query options. A key with `"filter_by_prefix"` will filter the returned channels. To get number of users subscribed to a presence-channel, specify an `"info"` key with value `"user_count"`. Pass in `nil` if you do not wish to specify any query attributes.

channelsParams := map[string]string{
    "filter_by_prefix": "presence-",
    "info":             "user_count",

channels, err := client.Channels(channelsParams)

//channels=> &{Channels:map[presence-chatroom:{UserCount:4} presence-notifications:{UserCount:31}  ]}

func (*Client) GetChannelUsers Uses

func (c *Client) GetChannelUsers(name string) (*Users, error)

Get 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) Notify Uses

func (c *Client) Notify(interests []string, pushNotification PushNotification) (*NotifyResponse, error)

Notify is used to send native push notifications via Apple APNS or Google GCM/FCM systems. Please make sure that you have provided a Client.PushNotificationHost, please see Pusher docs for details: https://pusher.com/docs/push_notifications

func (*Client) Trigger Uses

func (c *Client) Trigger(channel string, eventName string, data interface{}) (*BufferedEvents, error)

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 Uses

func (c *Client) TriggerBatch(batch []Event) (*BufferedEvents, error)

func (*Client) TriggerExclusive Uses

func (c *Client) TriggerExclusive(channel string, eventName string, data interface{}, socketID string) (*BufferedEvents, error)

This method allow you to exclude a recipient whose connection has that `socket_id` from receiving the event. You can read more here: http://pusher.com/docs/duplicates.

client.TriggerExclusive("a_channel", "event", data, "123.12")

func (*Client) TriggerMulti Uses

func (c *Client) TriggerMulti(channels []string, eventName string, data interface{}) (*BufferedEvents, error)

The same as `client.Trigger`, except one passes in a slice of `channels` as the first parameter. The maximum length of channels is 10.

client.TriggerMulti([]string{"a_channel", "another_channel"}, "event", data)

func (*Client) TriggerMultiExclusive Uses

func (c *Client) TriggerMultiExclusive(channels []string, eventName string, data interface{}, socketID string) (*BufferedEvents, error)

Excluding a recipient on a trigger to multiple channels.

client.TriggerMultiExclusive([]string{"a_channel", "another_channel"}, "event", data, "123.12")

func (*Client) Webhook Uses

func (c *Client) Webhook(header http.Header, body []byte) (*Webhook, error)

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.

This library provides a mechanism for checking that these POST requests are indeed from Pusher, by checking the token and authentication signature in the header of the request.

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 Event Uses

type Event struct {
    Channel  string  `json:"channel"`
    Name     string  `json:"name"`
    Data     string  `json:"data"`
    SocketId *string `json:"socket_id,omitempty"`

type MemberData Uses

type MemberData struct {
    UserId   string            `json:"user_id"`
    UserInfo map[string]string `json:"user_info,omitempty"`

A struct representing what to assign to a channel member, consisting of a `UserId` and any custom `UserInfo`.

type NotifyResponse Uses

type NotifyResponse struct {
    NumSubscribers int `json:"number_of_subscribers"`

NotifyResponse is returned from a successful PushNotification and contain the number of subscribers to those interests

type PushNotification Uses

type PushNotification struct {
    WebhookURL string      `json:"webhook_url,omitempty"`
    APNS       interface{} `json:"apns,omitempty"`
    GCM        interface{} `json:"gcm,omitempty"`
    FCM        interface{} `json:"fcm,omitempty"`

PushNotification is a type for requesting push notifications

type User Uses

type User struct {
    Id string `json:"id"`

Represents a user and contains their ID.

type Users Uses

type Users struct {
    List []User `json:"users"`

Represents a list of users in a presence-channel

type Webhook Uses

type Webhook struct {
    TimeMs int            `json:"time_ms"` // the timestamp of the request
    Events []WebhookEvent `json:"events"`  // the events associated with the webhook

This is a parsed form of a valid webhook received by the server.

type WebhookEvent Uses

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

Package pusher imports 16 packages (graph) and is imported by 3 packages. Updated 2017-07-26. Refresh now. Tools for package owners.