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

package pusher

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

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, 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

Index

Package Files

client.go crypto.go doc.go encoder.go request.go request_url.go response_parsing.go util.go webhook.go

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"`
}

Channel represents the information about a channel from the Pusher API.

type ChannelListItem Uses

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

ChannelListItem represents an item within ChannelsList

type ChannelsList Uses

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

ChannelsList 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
    Secure              bool   // true for HTTPS
    Cluster             string
    HTTPClient          *http.Client
    EncryptionMasterKey string //for E2E
}

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 `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 // 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 Uses

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

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 Uses

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

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 Uses

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

AuthenticatePresenceChannel allows you to authenticate a users subscription to a presence channel. It returns authentication 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.AuthenticatePresenceChannel(params, presenceData)

if err != nil {
	panic(err)
}

fmt.Fprintf(res, response)

func (*Client) AuthenticatePrivateChannel Uses

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

AuthenticatePrivateChannel allows you to authenticate a users subscription to a private channel. It returns 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 {
        panic(err)
    }

    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)

Channel allows you to 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)

Channels returns 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)

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) Trigger Uses

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

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 Uses

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

TriggerBatch triggers multiple events on multiple channels in a single call:

    client.TriggerBatch([]pusher.Event{
	    { Channel: "donut-1", Name: "ev1", Data: "d1" },
	    { Channel: "private-encrypted-secretdonut", Name: "ev2", Data: "d2" },
    })

func (*Client) TriggerExclusive Uses

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")

func (*Client) TriggerMulti Uses

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

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 Uses

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")

func (*Client) Webhook Uses

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

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 Uses

type EncryptedMessage struct {
    Nonce      string `json:"nonce"`
    Ciphertext string `json:"ciphertext"`
}

EncryptedMessage contains an encrypted message

type Event Uses

type Event struct {
    Channel  string
    Name     string
    Data     interface{}
    SocketID *string
}

Event stores all the data for one Event that can be triggered.

type MemberData Uses

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

type User struct {
    ID string `json:"id"`
}

User represents a user and contains their ID.

type Users Uses

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

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
}

Webhook is the 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
}

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

Package pusher imports 20 packages (graph) and is imported by 7 packages. Updated 2019-06-27. Refresh now. Tools for package owners.