gcm

package module
v0.0.0-...-984428c Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2015 License: MIT Imports: 8 Imported by: 0

README

gcm Build StatusCoverage Status

The Android SDK provides a nice convenience library (com.google.android.gcm.server) that greatly simplifies the interaction between Java-based application servers and Google's GCM servers. However, Google has not provided much support for application servers implemented in languages other than Java, specifically those written in the Go programming language. The gcm package helps to fill in this gap, providing a simple interface for sending GCM messages and automatically retrying requests in case of service unavailability.

Documentation: http://godoc.org/github.com/Aorioli/gcm

Getting Started

To install gcm, use go get:

go get github.com/Aorioli/gcm

Import gcm with the following:

import "github.com/Aorioli/gcm"

Sample Usage

Here is a quick sample illustrating how to send a message to the GCM server:

package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/Aorioli/gcm"
)

func main() {
	// Create the message to be sent.
	data := map[string]interface{}{"score": "5x1", "time": "15:10"}
	regIDs := []string{"4", "8", "15", "16", "23", "42"}
	m := new(gcm.Message)
	m.RegistrationIDs = regIDs
	m.Data = data

	// Create a Sender to send the message.
	sender := gcm.NewSender("sample_api_key", 2, time.Minute)

	// Send the message and receive the response after at most two retries.
	response, err := sender.Send(m)
	if err != nil {
		fmt.Println("Failed to send message:", err)
		return
	}

	/* ... */
}

Contributing

Open up an issue describing the bug, enhancement or whatever so it's open for discussion.

Fork the repo, make your changes on a separate branch from master and create a pull request.

Documentation

Overview

Package gcm is Google Cloud Messaging for application servers implemented using the Go programming language.

Index

Constants

View Source
const (
	// GcmSendEndpoint is the endpoint for sending messages to the GCM server.
	GcmSendEndpoint = "https://gcm-http.googleapis.com/gcm/send"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	APIKey     string
	RetryCount int
	HTTPClient *http.Client
}

Client abstracts the interaction between the application server and the GCM server. The developer must obtain an API key from the Google APIs Console page and pass it to the Sender so that it can perform authorized requests on the application server's behalf. To send a message to one or more devices use the Sender's Send method.

If your application server runs on Google AppEngine, you must use the "appengine/urlfetch" package to create the *http.Client as follows:

func handler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	client := urlfetch.Client(c)
	sender := &gcm.Sender{APIKey: key, Http: client}

	/* ... */
}

func NewSender

func NewSender(apiKey string, retryCount int, timeout time.Duration) *Client

NewSender creates a new Sender and sets a timeout on the http.Client

func (Client) Send

func (c Client) Send(m *Message) (*Response, error)

Send sends a message to the GCM server, retrying in case of service unavailability. A non-nil error is returned if a non-recoverable error occurs (i.e. if the response status is not "200 OK").

type Message

type Message struct {
	To                    string                 `json:"to"`
	RegistrationIDs       []string               `json:"registration_ids,omitempty"`
	CollapseKey           string                 `json:"collapse_key,omitempty"`
	Priority              string                 `json:"priority,omitempty"`
	ContentAvailable      bool                   `json:"content_available,omitempty"`
	DelayWhileIdle        bool                   `json:"delay_while_idle,omitempty"`
	TimeToLive            int                    `json:"time_to_live,omitempty"`
	RestrictedPackageName string                 `json:"restricted_package_name,omitempty"`
	DryRun                bool                   `json:"dry_run,omitempty"`
	Data                  map[string]interface{} `json:"data,omitempty"`
	Notification          *Notification          `json:"notification,omitempty"`
}

Message contains all fields that can be sent to the GCM API. Not all fields should be set, it's recommended to read the reference before sending anything at https://developers.google.com/cloud-messaging/http-server-ref

func (*Message) Request

func (m *Message) Request() (*http.Request, error)

Request creates a http.Request from a Message

func (*Message) Validate

func (m *Message) Validate() error

Validate checks some basic Message errors so invalid data isn't sent to GCM

type Notification

type Notification struct {
	Title        string `json:"title,omitempty"`
	Body         string `json:"body,omitempty"`
	Icon         string `json:"icon,omitempty"`
	Sound        string `json:"sound,omitempty"`
	Badge        string `json:"badge,omitempty"`
	Tag          string `json:"tag,omitempty"`
	Color        string `json:"color,omitempty"`
	ClickAction  string `json:"click_action,omitempty"`
	BodyLocKey   string `json:"body_loc_key,omitempty"`
	BodyLocArgs  string `json:"body_loc_args,omitempty"`
	TitleLocKey  string `json:"title_loc_key,omitempty"`
	TitleLocArgs string `json:"title_loc_args,omitempty"`
}

Notification containts all notification fields as defined in the GCM API reference

type Response

type Response struct {
	MessageID    int         `json:"message_id,omitempty"`
	Error        errorString `json:"error,omitempty"`
	MulticastID  int         `json:"multicast_id,omitempty"`
	Success      int         `json:"success,omitempty"`
	Failure      int         `json:"failure,omitempty"`
	CanonicalIDs int         `json:"canonical_ids,omitempty"`
	Results      []Result    `json:"results,omitempty"`
}

Response represents the GCM server's response to the application server's sent message. See the documentation for more information: https://developers.google.com/cloud-messaging/http-server-ref#interpret-downstream

func (Response) Ok

func (r Response) Ok() bool

Ok checks if the response contains any failures, canonical id changes or topic errors

type Result

type Result struct {
	MessageID      string      `json:"message_id,omitempty"`
	RegistrationID string      `json:"registration_id,omitempty"`
	Error          errorString `json:"error,omitempty"`
}

Result represents the status of a processed message.

type Sender

type Sender interface {
	Send(m *Message) (*Response, error)
}

Sender functions for sending messages to GCM

Jump to

Keyboard shortcuts

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