gcm

package module
v0.0.0-...-532ebb3 Latest Latest
Warning

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

Go to latest
Published: Jan 25, 2017 License: MIT Imports: 8 Imported by: 29

README

gcm

NOTE: I no longer maintain this library. Feel free to fork! :)

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/alexjlockwood/gcm

Getting Started

To install gcm, use go get:

go get github.com/alexjlockwood/gcm

Import gcm with the following:

import "github.com/alexjlockwood/gcm"

Sample Usage

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

package main

import (
	"fmt"
	"net/http"

	"github.com/alexjlockwood/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"}
	msg := gcm.NewMessage(data, regIDs...)

	// Create a Sender to send the message.
	sender := &gcm.Sender{ApiKey: "sample_api_key"}

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

	/* ... */
}

Note for Google AppEngine users

If your application server runs on Google AppEngine, you must import the appengine/urlfetch package and create the Sender as follows:

package sample

import (
	"appengine"
	"appengine/urlfetch"

	"github.com/alexjlockwood/gcm"
)

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

	/* ... */
}        

Documentation

Overview

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://android.googleapis.com/gcm/send"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Message

type Message struct {
	RegistrationIDs       []string               `json:"registration_ids"`
	CollapseKey           string                 `json:"collapse_key,omitempty"`
	Data                  map[string]interface{} `json:"data,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"`
}

Message is used by the application server to send a message to the GCM server. See the documentation for GCM Architectural Overview for more information: http://developer.android.com/google/gcm/gcm.html#send-msg

func NewMessage

func NewMessage(data map[string]interface{}, regIDs ...string) *Message

NewMessage returns a new Message with the specified payload and registration IDs.

type Response

type Response struct {
	MulticastID  int64    `json:"multicast_id"`
	Success      int      `json:"success"`
	Failure      int      `json:"failure"`
	CanonicalIDs int      `json:"canonical_ids"`
	Results      []Result `json:"results"`
}

Response represents the GCM server's response to the application server's sent message. See the documentation for GCM Architectural Overview for more information: http://developer.android.com/google/gcm/gcm.html#send-msg

type Result

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

Result represents the status of a processed message.

type Sender

type Sender struct {
	ApiKey string
	Http   *http.Client
}

Sender 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 or SendNoRetry methods.

If the Http field is nil, a zeroed http.Client will be allocated and used to send messages. 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 (*Sender) Send

func (s *Sender) Send(msg *Message, retries int) (*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").

Note that messages are retried using exponential backoff, and as a result, this method may block for several seconds.

func (*Sender) SendNoRetry

func (s *Sender) SendNoRetry(msg *Message) (*Response, error)

SendNoRetry sends a message to the GCM server without 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").

Jump to

Keyboard shortcuts

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