apns2

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Apr 1, 2016 License: MIT Imports: 9 Imported by: 0

README

Build Status GoDoc

Go Apns2

This project is under development

Go package for HTTP/2 Apple Push Notification Service.

Installation

Via go-get:

$ go get github.com/sger/go-apns2
$ cd go-apns2/_examples
$ cd basic
$ go build
$ ./basic

Documentation

$ godoc .
$ godoc -http=:6060

Usage

Simple example

package main

import (
	"fmt"
	"log"

	"github.com/sger/go-apns2"
	"github.com/sger/go-apns2/certificate"
)

func main() {
	var deviceToken = "c7800a79efffe8ffc01b280717a936937cb69f8ca307545eb6983c60f12e167a"
	var filename = "../certs/PushChatKey.p12"
	var password = "pushchat"

	// Setup payload must contains an aps root label and alert message
	payload := apns2.Payload{
		Alert: apns2.Alert{
			Body: "Testing HTTP 2"},
		Badge: 5,
	}

	// Parse the certificate
	cert, err := certificate.ReadP12File(filename, password)
	if err != nil {
		log.Fatal(err)
	}

	// Setup a new http client with pass the Certificate
	// and host environment (apns2.Development, apns2.Production)
	client, err := apns2.NewClient(cert, apns2.Development)

	if err != nil {
		log.Fatal(err)
	}

	// Send the Push Notification
	resp, err := client.SendPush(payload, deviceToken, &apns2.Headers{})

	if err != nil {
		log.Fatal(err)
	}

	// Returns ApnsResponse struct
	/*
		type ApnsResponse struct {
		StatusCode            int
		StatusCodeDescription string
		ApnsID                string `json:"apns-id,omitempty"`
		Reason                string `json:"reason,omitempty"`
	}*/
	fmt.Println(resp)
}

Goroutines and channels example

package main

import (
	"fmt"
	"log"
	"time"

	"github.com/sger/go-apns2"
	"github.com/sger/go-apns2/certificate"
)

var status bool
var payloads []apns2.Payload
var payloadsProcessed int
var totalPayloads int
var apns []*apns2.ApnsResponse

func main() {
	status = true
	statusChannel := make(chan int)
	payloadChannel := make(chan *apns2.ApnsResponse)
	totalPayloads = 0

	// Creating 1000 payloads
	for i := 0; i < 1000; i++ {
		message := fmt.Sprintf("Hello World %v!", i)
		payload := apns2.Payload{
			Alert: apns2.Alert{
				Body: message},
		}
		payloads = append(payloads, payload)
	}

	payloadsProcessed = 0
	totalPayloads = len(payloads)

	// goroutines
	go sendPayloads(statusChannel, payloadChannel)
	go processPayloadResponses(payloadChannel)

	for {
		if status == false {
			for _, id := range apns {
				fmt.Println(id)
			}
			fmt.Println("Done sending ", totalPayloads, " payloads")
			break
		}
		select {
		case sC := <-statusChannel:
			fmt.Println("Payload received on StatusChannel", sC)
			payloadsProcessed++
			if payloadsProcessed == totalPayloads {
				fmt.Println("Received all Payloads")
				status = false
				close(statusChannel)
				close(payloadChannel)
			}
		}
	}
}

func sendPayloads(statusChannel chan int, payloadChannel chan *apns2.ApnsResponse) {
	time.Sleep(time.Millisecond * 1)
	fmt.Println("Sending", len(payloads), "payloads")

	var deviceToken = "c7800a79efffe8ffc01b280717a936937cb69f8ca307545eb6983c60f12e167a"
	var filename = "../certs/PushChatKey.p12"
	var password = "pushchat"

	cert, err := certificate.ReadP12File(filename, password)
	if err != nil {
		log.Fatal(err)
	}

	// Setup a new http client
	client, err := apns2.NewClient(cert, apns2.Development)

	if err != nil {
		log.Fatal(err)
	}

	for i := 0; i < totalPayloads; i++ {
		fmt.Println("sending payload ", i, payloads[i])
		resp, err := client.SendPush(payloads[i], deviceToken, &apns2.Headers{})
		if err != nil {
			log.Fatal(err)
		}
		payloadChannel <- resp
		statusChannel <- 0
	}
}

func processPayloadResponses(payloadChannel chan *apns2.ApnsResponse) {
	for {
		select {
		case pC := <-payloadChannel:
			apns = append(apns, pC)
		}
	}
}

TODO

  • Pem Support
  • Tests
  • Error Handling
  • Support for Feedback service

Author

Spiros Gerokostas

License

Go Apns2 is available under the MIT license. See the LICENSE file for more info.

Documentation

Index

Constants

View Source
const (
	Development = "https://api.development.push.apple.com"
	Production  = "https://api.push.apple.com"
)

Apple Development and Production URLs

View Source
const (
	ApnsID         = "apns-id"
	ApnsExpiration = "apns-expiration"
	ApnsPriority   = "apns-priority"
	ApnsTopic      = "apns-topic"
)

Request headers

Variables

This section is empty.

Functions

This section is empty.

Types

type Alert

type Alert struct {
	// A short string describing the purpose of the notification. Apple Watch
	// displays this string as part of the notification interface. This
	// string is displayed only briefly and should be crafted so that
	// it can be understood quickly. This key was added in iOS 8.2.
	Title string `json:"title,omitempty"`

	// The text of the alert message.
	Body string `json:"body,omitempty"`

	// The key to a title string in the Localizable.strings file for the current localization.
	// The key string can be formatted with %@ and %n$@ specifiers to take the variables
	// specified in the title-loc-args array. See Localized Formatted Strings for
	// more information.This key was added in iOS 8.2.
	TitleLocKey string `json:"title-loc-key,omitempty"`

	// Variable string values to appear in place of the format specifiers in title-loc-key.
	// See Localized Formatted Strings for more information.This key was added in iOS 8.2.
	TitleLocArgs []string `json:"title-loc-args,omitempty"`

	// If a string is specified, the system displays an alert that includes the Close and View buttons.
	// The string is used as a key to get a localized string in the current localization to use
	// for the right button’s title instead of “View”. See Localized Formatted Strings
	// for more information.
	ActionLocKey string `json:"action-loc-key,omitempty"`

	// A key to an alert-message string in a Localizable.strings file for the current
	// localization (which is set by the user’s language preference).The key string
	// can be formatted with %@ and %n$@ specifiers to take the variables
	// specified in the loc-args array. See Localized Formatted
	// Strings for more information.
	LocKey string `json:"loc-key,omitempty"`

	// Variable string values to appear in place of the format specifiers in loc-key. See Localized Formatted Strings for more information.
	LocArgs []string `json:"loc-args,omitempty"`

	// The filename of an image file in the app bundle; it may include the extension or omit it.
	// The image is used as the launch image when users tap the action button or move the
	// action slider.If this property is not specified, the system either uses the
	// previous snapshot,uses the image identified by the UILaunchImageFile key
	// in the app’s Info.plist file, or falls back to Default.png.
	// This property was added in iOS 4.0.
	LaunchImage string `json:"launch-image,omitempty"`
}

Alert If this property is included, the system displays a standard alert or a banner, based on the user’s setting. You can specify a string or a dictionary as the value of alert.

type ApnsResponse

type ApnsResponse struct {
	StatusCode            int
	StatusCodeDescription string
	ApnsID                string `json:"apns-id,omitempty"`
	Reason                string `json:"reason,omitempty"`
}

ApnsResponse contains apns-id, reason, status code, status code description.

type Client

type Client struct {
	HTTPClient  *http.Client
	Certificate tls.Certificate
	Host        string
}

Client struct with HTTPClient, Certificate, Host as parameters.

func NewClient

func NewClient(certificate tls.Certificate, host string) (*Client, error)

NewClient constructor tls.Certificate parameter.

func (*Client) SendPush

func (c *Client) SendPush(payload interface{}, deviceToken string, headers *Headers) (*ApnsResponse, error)

SendPush a push notification with payload ([]byte), device token, *Headers returns ApnsResponse struct

type ErrorResponse

type ErrorResponse struct {
	Reason    string `json:"reason,omitempty"`
	Timestamp int64  `json:"timestamp,omitempty"`
}

ErrorResponse contains reason, timestamp

type Headers

type Headers struct {
	ID          string
	Expiration  time.Time
	LowPriority bool
	Topic       string
}

Headers request headers for apple push notification

func (*Headers) Set

func (h *Headers) Set(header http.Header)

Set request headers

type Payload

type Payload struct {
	// If this property is included, the system displays a standard alert or a banner, based on the user’s setting.
	Alert Alert

	// The number to display as the badge of the app icon. If this
	// property is absent, the badge is not changed. To remove
	// the badge, set the value of this property to 0.
	Badge uint

	// The name of a sound file in the app bundle or in the Library/Sounds folder of the app’s data container. The sound
	// in this file is played as an alert. If the sound file doesn’t exist or default is specified as the value,
	// the default alert sound is played.The audio must be in one of the audio data formats that are
	// compatible with system sounds.
	Sound string

	// Provide this key with a value of 1 to indicate that new content is available. Including
	// this key and value means that when your app is launched in the background or resumed,
	// application:didReceiveRemoteNotification:fetchCompletionHandler: is called.
	ContentAvailable bool

	// Provide this key with a string value that represents the identifier
	// property of the UIMutableUserNotificationCategory object
	// you created to define custom actions
	Category string
}

Payload For each notification, compose a JSON dictionary object (as defined by RFC 4627). This dictionary must contain another dictionary identified by the aps key. The aps dictionary can contain one or more properties that specify the following user notification types: An alert message to display to the user A number to badge the app icon with A sound to play.

func (*Payload) Map

func (p *Payload) Map() map[string]interface{}

Map returns a valid payload

func (Payload) MarshalJSON

func (p Payload) MarshalJSON() ([]byte, error)

MarshalJSON returns []byte, error

Directories

Path Synopsis
_examples
pem

Jump to

Keyboard shortcuts

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