Documentation ¶
Overview ¶
Package apns2 is a go Apple Push Notification Service (APNs) provider that allows you to send remote notifications to your iOS, tvOS, and OS X apps, using the new APNs HTTP/2 network protocol.
Index ¶
- Constants
- Variables
- type Client
- func (c *Client) CloseIdleConnections()
- func (c *Client) Development() *Client
- func (c *Client) DialTLS(network, addr string, cfg *tls.Config) (conn net.Conn, err error)
- func (c *Client) DisablePinging() bool
- func (c *Client) EnablePinging(willHandleDrops bool) (<-chan struct{}, bool)
- func (c *Client) EnableProxy(proxyURI string) error
- func (c *Client) Production() *Client
- func (c *Client) Push(n *Notification) (*Response, error)
- func (c *Client) PushWithContext(ctx Context, n *Notification) (*Response, error)
- func (c *Client) ResetHTTPClient()
- type ClientManager
- type Context
- type Notification
- type Response
- type Time
Constants ¶
const ( HostDevelopment = "https://api.development.push.apple.com" HostProduction = "https://api.push.apple.com" )
Apple HTTP/2 Development & Production urls
const ( // PriorityLow will tell APNs to send the push message at a time that takes // into account power considerations for the device. Notifications with this // priority might be grouped and delivered in bursts. They are throttled, and // in some cases are not delivered. PriorityLow = 5 // PriorityHigh will tell APNs to send the push message immediately. // Notifications with this priority must trigger an alert, sound, or badge on // the target device. It is an error to use this priority for a push // notification that contains only the content-available key. PriorityHigh = 10 )
const ( // 400 The collapse identifier exceeds the maximum allowed size ReasonBadCollapseID = "BadCollapseId" // 400 The specified device token was bad. Verify that the request contains a // valid token and that the token matches the environment. ReasonBadDeviceToken = "BadDeviceToken" // 400 The apns-expiration value is bad. ReasonBadExpirationDate = "BadExpirationDate" // 400 The apns-id value is bad. ReasonBadMessageID = "BadMessageId" // 400 The apns-priority value is bad. ReasonBadPriority = "BadPriority" // 400 The apns-topic was invalid. ReasonBadTopic = "BadTopic" // 400 The device token does not match the specified topic. ReasonDeviceTokenNotForTopic = "DeviceTokenNotForTopic" // 400 One or more headers were repeated. ReasonDuplicateHeaders = "DuplicateHeaders" // 400 Idle time out. ReasonIdleTimeout = "IdleTimeout" // 400 The device token is not specified in the request :path. Verify that the // :path header contains the device token. ReasonMissingDeviceToken = "MissingDeviceToken" // 400 The apns-topic header of the request was not specified and was // required. The apns-topic header is mandatory when the client is connected // using a certificate that supports multiple topics. ReasonMissingTopic = "MissingTopic" // 400 The message payload was empty. ReasonPayloadEmpty = "PayloadEmpty" // 400 Pushing to this topic is not allowed. ReasonTopicDisallowed = "TopicDisallowed" // 403 The certificate was bad. ReasonBadCertificate = "BadCertificate" // 403 The client certificate was for the wrong environment. ReasonBadCertificateEnvironment = "BadCertificateEnvironment" // 403 The provider token is stale and a new token should be generated. ReasonExpiredProviderToken = "ExpiredProviderToken" // 403 The specified action is not allowed. ReasonForbidden = "Forbidden" // 403 The provider token is not valid or the token signature could not be // verified. ReasonInvalidProviderToken = "InvalidProviderToken" // 403 No provider certificate was used to connect to APNs and Authorization // header was missing or no provider token was specified. ReasonMissingProviderToken = "MissingProviderToken" // 404 The request contained a bad :path value. ReasonBadPath = "BadPath" // 405 The specified :method was not POST. ReasonMethodNotAllowed = "MethodNotAllowed" // 410 The device token is inactive for the specified topic. ReasonUnregistered = "Unregistered" // 413 The message payload was too large. See Creating the Remote Notification // Payload in the Apple Local and Remote Notification Programming Guide for // details on maximum payload size. ReasonPayloadTooLarge = "PayloadTooLarge" // 429 The provider token is being updated too often. ReasonTooManyProviderTokenUpdates = "TooManyProviderTokenUpdates" // 429 Too many requests were made consecutively to the same device token. ReasonTooManyRequests = "TooManyRequests" // 500 An internal server error occurred. ReasonInternalServerError = "InternalServerError" ReasonServiceUnavailable = "ServiceUnavailable" // 503 The server is shutting down. ReasonShutdown = "Shutdown" )
The possible Reason error codes returned from APNs. From table 8-6 in the Apple Local and Remote Notification Programming Guide.
const StatusSent = http.StatusOK
StatusSent is a 200 response.
Variables ¶
var ( // TLSDialTimeout is the maximum amount of time a dial will wait for a connect // to complete. TLSDialTimeout = 20 * time.Second // HTTPClientTimeout specifies a time limit for requests made by the // HTTPClient. The timeout includes connection time, any redirects, // and reading the response body. HTTPClientTimeout = 30 * time.Second // TCPKeepAlive specifies the keep-alive period for an active network // connection. If zero, keep-alives are not enabled. TCPKeepAlive = 10 * time.Second // PingPongFrequency is the interval with which a client will PING APNs // servers. PingPongFrequency = 10 * time.Second )
var DefaultHost = HostDevelopment
DefaultHost is a mutable var for testing purposes
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct { Host string Certificate tls.Certificate Token *token.Token HTTPClient *http.Client // contains filtered or unexported fields }
Client represents a connection with the APNs
func NewClient ¶
func NewClient(certificate tls.Certificate) *Client
NewClient returns a new Client with an underlying http.Client configured with the correct APNs HTTP/2 transport settings. It does not connect to the APNs until the first Notification is sent via the Push method.
As per the Apple APNs Provider API, you should keep a handle on this client so that you can keep your connections with APNs open across multiple notifications; don’t repeatedly open and close connections. APNs treats rapid connection and disconnection as a denial-of-service attack.
If your use case involves multiple long-lived connections, consider using the ClientManager, which manages clients for you.
Alternatively, you can keep the clients connection healthy by calling EnablePinging, which will send PING frames to APNs servers with the interval specified via PingPongFrequency.
func NewTokenClient ¶
NewTokenClient returns a new Client with an underlying http.Client configured with the correct APNs HTTP/2 transport settings. It does not connect to the APNs until the first Notification is sent via the Push method.
As per the Apple APNs Provider API, you should keep a handle on this client so that you can keep your connections with APNs open across multiple notifications; don’t repeatedly open and close connections. APNs treats rapid connection and disconnection as a denial-of-service attack.
func (*Client) CloseIdleConnections ¶
func (c *Client) CloseIdleConnections()
CloseIdleConnections closes any underlying connections which were previously connected from previous requests but are now sitting idle. It will not interrupt any connections currently in use.
func (*Client) Development ¶
Development sets the Client to use the APNs development push endpoint.
func (*Client) DialTLS ¶
DialTLS is the default dial function for creating TLS connections for non-proxied HTTPS requests.
func (*Client) DisablePinging ¶
DisablePinging stops the pinging operation associated with the client, if there's any, and returns a boolean that indicates if the call has successfully stopped the pinging operation.
func (*Client) EnablePinging ¶
EnablePinging tries to send PING frames to APNs servers whenever the client has a valid connection. If the willHandleDrops parameter is set to true, this function returns a read-only channel that gets notified when pinging fails. This allows the user to take actions to preemptively reinitialize the client's connection. The second return value indicates whether the call has successfully enabled pinging.
func (*Client) EnableProxy ¶
func (*Client) Production ¶
Production sets the Client to use the APNs production push endpoint.
func (*Client) Push ¶
func (c *Client) Push(n *Notification) (*Response, error)
Push sends a Notification to the APNs gateway. If the underlying http.Client is not currently connected, this method will attempt to reconnect transparently before sending the notification. It will return a Response indicating whether the notification was accepted or rejected by the APNs gateway, or an error if something goes wrong.
Use PushWithContext if you need better cancellation and timeout control.
func (*Client) PushWithContext ¶
func (c *Client) PushWithContext(ctx Context, n *Notification) (*Response, error)
PushWithContext sends a Notification to the APNs gateway. Context carries a deadline and a cancellation signal and allows you to close long running requests when the context timeout is exceeded. Context can be nil, for backwards compatibility.
If the underlying http.Client is not currently connected, this method will attempt to reconnect transparently before sending the notification. It will return a Response indicating whether the notification was accepted or rejected by the APNs gateway, or an error if something goes wrong.
func (*Client) ResetHTTPClient ¶
func (c *Client) ResetHTTPClient()
type ClientManager ¶
type ClientManager struct { // MaxSize is the maximum number of clients allowed in the manager. When // this limit is reached, the least recently used client is evicted. Set // zero for no limit. MaxSize int // MaxAge is the maximum age of clients in the manager. Upon retrieval, if // a client has remained unused in the manager for this duration or longer, // it is evicted and nil is returned. Set zero to disable this // functionality. MaxAge time.Duration // Factory is the function which constructs clients if not found in the // manager. Factory func(certificate tls.Certificate) *Client // contains filtered or unexported fields }
ClientManager is a way to manage multiple connections to the APNs.
func NewClientManager ¶
func NewClientManager() *ClientManager
NewClientManager returns a new ClientManager for prolonged, concurrent usage of multiple APNs clients. ClientManager is flexible enough to work best for your use case. When a client is not found in the manager, Get will return the result of calling Factory, which can be a Client or nil.
Having multiple clients per certificate in the manager is not allowed.
By default, MaxSize is 64, MaxAge is 10 minutes, and Factory always returns a Client with default options.
func (*ClientManager) Add ¶
func (m *ClientManager) Add(client *Client)
Add adds a Client to the manager. You can use this to individually configure Clients in the manager.
func (*ClientManager) Get ¶
func (m *ClientManager) Get(certificate tls.Certificate) *Client
Get gets a Client from the manager. If a Client is not found in the manager or if a Client has remained in the manager longer than MaxAge, Get will call the ClientManager's Factory function, store the result in the manager if non-nil, and return it.
func (*ClientManager) Len ¶
func (m *ClientManager) Len() int
Len returns the current size of the ClientManager.
type Context ¶
A Context carries a deadline, a cancellation signal, and other values across API boundaries.
Context's methods may be called by multiple goroutines simultaneously.
type Notification ¶
type Notification struct { // An optional canonical UUID that identifies the notification. The canonical // form is 32 lowercase hexadecimal digits, displayed in five groups separated // by hyphens in the form 8-4-4-4-12. An example UUID is as follows: // // 123e4567-e89b-12d3-a456-42665544000 // // If you don't set this, a new UUID is created by APNs and returned in the // response. ApnsID string // A string which allows multiple notifications with the same collapse identifier // to be displayed to the user as a single notification. The value should not // exceed 64 bytes. CollapseID string // A string containing hexadecimal bytes of the device token for the target device. DeviceToken string // The topic of the remote notification, which is typically the bundle ID for // your app. The certificate you create in the Apple Developer Member Center // must include the capability for this topic. If your certificate includes // multiple topics, you must specify a value for this header. If you omit this // header and your APNs certificate does not specify multiple topics, the APNs // server uses the certificate’s Subject as the default topic. Topic string // An optional time at which the notification is no longer valid and can be // discarded by APNs. If this value is in the past, APNs treats the // notification as if it expires immediately and does not store the // notification or attempt to redeliver it. If this value is left as the // default (ie, Expiration.IsZero()) an expiration header will not added to the // http request. Expiration time.Time // The priority of the notification. Specify ether apns.PriorityHigh (10) or // apns.PriorityLow (5) If you don't set this, the APNs server will set the // priority to 10. Priority int // A byte array containing the JSON-encoded payload of this push notification. // Refer to "The Remote Notification Payload" section in the Apple Local and // Remote Notification Programming Guide for more info. Payload interface{} }
Notification represents the the data and metadata for a APNs Remote Notification.
func (*Notification) MarshalJSON ¶
func (n *Notification) MarshalJSON() ([]byte, error)
MarshalJSON converts the notification payload to JSON.
type Response ¶
type Response struct { // The HTTP status code returned by APNs. // A 200 value indicates that the notification was successfully sent. // For a list of other possible status codes, see table 6-4 in the Apple Local // and Remote Notification Programming Guide. StatusCode int // The APNs error string indicating the reason for the notification failure (if // any). The error code is specified as a string. For a list of possible // values, see the Reason constants above. // If the notification was accepted, this value will be "". Reason string // The APNs ApnsID value from the Notification. If you didn't set an ApnsID on the // Notification, this will be a new unique UUID which has been created by APNs. ApnsID string // If the value of StatusCode is 410, this is the last time at which APNs // confirmed that the device token was no longer valid for the topic. Timestamp Time }
Response represents a result from the APNs gateway indicating whether a notification was accepted or rejected and (if applicable) the metadata surrounding the rejection.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
_example
|
|
Package certificate contains functions to load an Apple APNs PKCS#12 or PEM certificate from either an in memory byte array or a local file.
|
Package certificate contains functions to load an Apple APNs PKCS#12 or PEM certificate from either an in memory byte array or a local file. |
Package payload is a helper package which contains a payload builder to make constructing notification payloads easier.
|
Package payload is a helper package which contains a payload builder to make constructing notification payloads easier. |