exponent

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2025 License: Apache-2.0 Imports: 7 Imported by: 0

README

exponent

Send push notifications to Expo apps using Golang

revised version of: https://github.com/oliveroneill/exponent-server-sdk-golang/tree/master

Documentation

Go Reference

Installation

go get github.com/9ssi7/exponent

Usage

package main

import (
	"context"
	"time"

	"github.com/9ssi7/exponent"
)

func main() {
	c := exponent.NewClient(exponent.WithAccessToken("your-access-token"))

	tkn := exponent.MustParseToken("ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	res, err := c.PublishSingle(ctx, &exponent.Message{
		To:       []*exponent.Token{tkn},
		Body:     "This is a test notification",
		Data:     exponent.Data{"withSome": "data"},
		Sound:    "default",
		Title:    "Notification Title",
		Priority: exponent.DefaultPriority,
	})

	if err != nil {
		panic(err)
	}

	for _, receipt := range res {
		if receipt.IsOk() {
			println("Notification sent successfully")
		} else {
			println("Notification failed")
		}
	}
}

Contributing

We welcome contributions! Please see our Contribution Guidelines for details.

License

This project is licensed under the Apache License. See LICENSE for more details.

Documentation

Index

Constants

View Source
const (
	// NormalPriority is a priority used in PushMessage
	NormalPriority Priority = "normal"
	// HighPriority is a priority used in PushMessage
	HighPriority Priority = "high"
	// DefaultPriority is the standard priority used in PushMessage
	DefaultPriority Priority = "default"

	// ErrorMsgDeviceNotRegistered indicates the token is invalid
	ErrorMsgDeviceNotRegistered ErrorMsg = "DeviceNotRegistered"
	// ErrorMsgTooBig indicates the message went over payload size of 4096 bytes
	ErrorMsgTooBig ErrorMsg = "MessageTooBig"
	// ErrorMsgRateExceeded indicates messages have been sent too frequently
	ErrorMsgRateExceeded ErrorMsg = "MessageRateExceeded"
	// ErrMsgMalformedToken is returned if a token does not start with 'ExponentPushToken'
	ErrMsgMalformedToken ErrorMsg = "token should start with ExponentPushToken"
)

Variables

This section is empty.

Functions

func IsPushTokenValid

func IsPushTokenValid(token string) bool

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

func NewClient

func NewClient(opts ...Option) *Client

func (*Client) Publish

func (c *Client) Publish(ctx context.Context, msgs []*Message) ([]*MessageResponse, error)

PublishMultiple sends multiple push notifications at once @param msgs: An array of Message objects. @return an array of MessageResponse objects which contains the results. @return error if the request failed

func (*Client) PublishSingle

func (c *Client) PublishSingle(ctx context.Context, msg *Message) ([]*MessageResponse, error)

Publish sends a single push notification @param msg: A Message object @return an array of MessageResponse objects which contains the results. @return error if any requests failed

type Config

type Config struct {
	Host       string
	ApiURL     string
	AcessToken string
	HttpClient *http.Client
}

type Data

type Data map[string]string

type ErrorMsg

type ErrorMsg string

type Message

type Message struct {
	// An Expo push token or an array of Expo push tokens specifying the recipient(s) of this message.
	To []*Token `json:"to"`
	// The title to display in the notification. On iOS, this is displayed only on Apple Watch.
	Title string `json:"title,omitempty"`
	// The message to display in the notification.
	Body string `json:"body"`
	// A dict of extra data to pass inside of the push notification. The total notification payload must be at most 4096 bytes.
	Data Data `json:"data,omitempty"`
	// A sound to play when the recipient receives this notification.
	// Specify "default" to play the device's default notification sound, or omit this field to play no sound.
	Sound string `json:"sound,omitempty"`
	// The number of seconds for which the message may be kept around for redelivery if it hasn't been delivered yet. Defaults to 0.
	TTL int `json:"ttl,omitempty"`
	// UNIX timestamp for when this message expires. It has the same effect as ttl, and is just an absolute timestamp instead of a relative one.
	Expiration int64 `json:"expiration,omitempty"`
	// Delivery priority of the message. Use the *Priority constants specified above.
	Priority Priority `json:"priority,omitempty"`
	// An integer representing the unread notification count.
	// This currently only affects iOS. Specify 0 to clear the badge count.
	Badge int `json:"badge,omitempty"`
	// ID of the Notification Channel through which to display this notification on Android devices.
	ChannelID   string       `json:"channelId,omitempty"`
	RichContent *RichContent `json:"richContent,omitempty"`
}

is an object that describes a push notification request.

type MessageResponse

type MessageResponse struct {
	MessageItem *Message
	ID          string `json:"id"`
	Status      string `json:"status"`
	Message     string `json:"message"`
	Details     Data   `json:"details"`
}

PushResponse is a wrapper class for a push notification response. A successful single push notification:

{'status': 'ok'}

An invalid push token

{'status': 'error',
 'message': '"adsf" is not a registered push notification recipient'}

func (*MessageResponse) IsOk

func (r *MessageResponse) IsOk() bool

type Option

type Option func(*Config)

func WithAccessToken

func WithAccessToken(accessToken string) Option

func WithApiURL

func WithApiURL(apiURL string) Option

func WithHost

func WithHost(host string) Option

func WithHttpClient

func WithHttpClient(httpClient *http.Client) Option

type Priority

type Priority string

type Response

type Response struct {
	Data   []*MessageResponse `json:"data"`
	Errors []Data             `json:"errors"`
}

Response is the HTTP response returned from an Expo publish HTTP request

type RichContent added in v0.0.4

type RichContent struct {
	Image string `json:"image,omitempty"`
}

type ServerError

type ServerError struct {
	Message      string
	Response     *http.Response
	ResponseData *Response
	Errors       []Data
}

ServerError is raised when the push token server is not behaving as expected For example, invalid push notification arguments result in a different style of error. Instead of a "data" array containing errors per notification, an "error" array is returned. {"errors": [

{"code": "API_ERROR",
 "message": "child \"to\" fails because [\"to\" must be a string]. \"value\" must be an array."
}

]}

func NewServerError

func NewServerError(message string, response *http.Response,
	responseData *Response,
	errors []Data) *ServerError

NewServerError creates a new PushServerError object

func (*ServerError) Error

func (e *ServerError) Error() string

type Token

type Token string

func MustParseToken

func MustParseToken(token string) *Token

func ParseToken

func ParseToken(token string) (*Token, error)

ParseToken returns a token and may return an error if the input token is invalid

Jump to

Keyboard shortcuts

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