fcm

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Mar 6, 2019 License: MIT Imports: 12 Imported by: 0

README

go-fcm

(in beta!)

GoDoc Go Report Card

This project basicly was forked from github.com/edganiukov/fcm and github.com/appleboy/go-fcm.

Golang client library for Firebase Cloud Messaging. Implemented only HTTP client.

More information on Firebase Cloud Messaging

Feature

  • Send messages to a topic
  • Send messages to a device list
  • Supports condition attribute (fcm only)

Difference with appleboy package

  • Go modules with semantic versioning
  • valyala/fasthttp client instead of net/http
  • mailru/easyjson client instead of encoding/json
  • Send() returns original body ([]byte) too (if FCM answer changed you can parse by yourself and not wait for package update)
  • Some optimizations

Getting Started

To install gofcm, use go get:

go get github.com/riftbit/gofcm

Sample Usage

Here is a simple example illustrating how to use FCM library:

package main

import (
	"log"

	"github.com/riftbit/gofcm"
)

func main() {
	// Create the message to be sent.
	msg := &fcm.Message{
		To: "sample_device_token",
		Data: map[string]interface{}{
			"foo": "bar",
		},
	}

	// Create a FCM client to send the message.
	client, err := fcm.NewClient("sample_api_key")
	if err != nil {
		log.Fatalln(err)
	}

	// Send the message and receive the response without retries.
	response, body, err := client.Send(msg)
	if err != nil {
		log.Fatalln(err)
	}

	log.Printf("%#v\n", response)
	log.Printf("%#v\n", body)
}

Documentation

Index

Constants

View Source
const (
	// DefaultEndpoint contains endpoint URL of FCM service.
	DefaultEndpoint = "https://fcm.googleapis.com/fcm/send"

	// DefaultTimeout duration in second
	DefaultTimeout time.Duration = 30 * time.Second
)

Variables

View Source
var (
	// ErrInvalidMessage occurs if push notitication message is nil.
	ErrInvalidMessage = errors.New("message is invalid")

	// ErrInvalidTarget occurs if message topic is empty.
	ErrInvalidTarget = errors.New("topic is invalid or registration ids are not set")

	// ErrToManyRegIDs occurs when registration ids more then 1000.
	ErrToManyRegIDs = errors.New("too many registrations ids")

	// ErrInvalidTimeToLive occurs if TimeToLive more then 2419200.
	ErrInvalidTimeToLive = errors.New("messages time-to-live is invalid")
)
View Source
var (
	// ErrMissingRegistration occurs if registration token is not set.
	ErrMissingRegistration = errors.New("missing registration token")

	// ErrInvalidRegistration occurs if registration token is invalid.
	ErrInvalidRegistration = errors.New("invalid registration token")

	// ErrNotRegistered occurs when application was deleted from device and
	// token is not registered in FCM.
	ErrNotRegistered = errors.New("unregistered device")

	// ErrInvalidPackageName occurs if package name in message is invalid.
	ErrInvalidPackageName = errors.New("invalid package name")

	// ErrMismatchSenderID occurs when application has a new registration token.
	ErrMismatchSenderID = errors.New("mismatched sender id")

	// ErrMessageTooBig occurs when message is too big.
	ErrMessageTooBig = errors.New("message is too big")

	// ErrInvalidDataKey occurs if data key is invalid.
	ErrInvalidDataKey = errors.New("invalid data key")

	// ErrInvalidTTL occurs when message has invalid TTL.
	ErrInvalidTTL = errors.New("invalid time to live")

	// ErrUnavailable occurs when FCM service is unavailable. It makes sense
	// to retry after this error.
	ErrUnavailable = connectionError("timeout")

	// ErrInternalServerError is internal FCM error. It makes sense to retry
	// after this error.
	ErrInternalServerError = serverError("internal server error")

	// ErrDeviceMessageRateExceeded occurs when client sent to many requests to
	// the device.
	ErrDeviceMessageRateExceeded = errors.New("device message rate exceeded")

	// ErrTopicsMessageRateExceeded occurs when client sent to many requests to
	// the topics.
	ErrTopicsMessageRateExceeded = errors.New("topics message rate exceeded")

	// ErrInvalidParameters occurs when provided parameters have the right name and type
	ErrInvalidParameters = errors.New("check that the provided parameters have the right name and type")

	// ErrUnknown for unknown error type
	ErrUnknown = errors.New("unknown error type")
)
View Source
var (
	// ErrInvalidAPIKey occurs if API key is not set.
	ErrInvalidAPIKey = errors.New("client API Key is invalid")
)

Functions

func FasthttpHTTPDialer added in v0.0.2

func FasthttpHTTPDialer(proxyAddr string) fasthttp.DialFunc

func GetErrorByString added in v0.0.3

func GetErrorByString(errString string) error

func IsUnregisterByError added in v0.0.3

func IsUnregisterByError(err error) bool

func IsUnregisterByErrorString added in v0.0.4

func IsUnregisterByErrorString(errString string) bool

Types

type Client

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

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

If the `HTTP` field is nil, a zeroed http.Client will be allocated and used to send messages.

func NewClient

func NewClient(apiKey string, opts ...Option) (*Client, error)

NewClient creates new Firebase Cloud Messaging Client based on API key and with default endpoint and http client.

func (*Client) Send

func (c *Client) Send(msg *Message) (*Response, []byte, error)

Send sends a message to the FCM 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").

func (*Client) SendWithRetry

func (c *Client) SendWithRetry(msg *Message, retryAttempts int) (*Response, []byte, error)

SendWithRetry sends a message to the FCM server with defined number of retrying in case of temporary error.

type Message

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

Message represents list of targets, options, and payload for HTTP JSON messages.

func (Message) MarshalEasyJSON

func (v Message) MarshalEasyJSON(w *jwriter.Writer)

MarshalEasyJSON supports easyjson.Marshaler interface

func (Message) MarshalJSON

func (v Message) MarshalJSON() ([]byte, error)

MarshalJSON supports json.Marshaler interface

func (*Message) UnmarshalEasyJSON

func (v *Message) UnmarshalEasyJSON(l *jlexer.Lexer)

UnmarshalEasyJSON supports easyjson.Unmarshaler interface

func (*Message) UnmarshalJSON

func (v *Message) UnmarshalJSON(data []byte) error

UnmarshalJSON supports json.Unmarshaler interface

func (*Message) Validate

func (msg *Message) Validate() error

Validate returns an error if the message is not well-formed.

type Notification

type Notification struct {
	Title        string `json:"title,omitempty"`
	Body         string `json:"body,omitempty"`
	ChannelID    string `json:"android_channel_id,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 specifies the predefined, user-visible key-value pairs of the notification payload.

func (Notification) MarshalEasyJSON

func (v Notification) MarshalEasyJSON(w *jwriter.Writer)

MarshalEasyJSON supports easyjson.Marshaler interface

func (Notification) MarshalJSON

func (v Notification) MarshalJSON() ([]byte, error)

MarshalJSON supports json.Marshaler interface

func (*Notification) UnmarshalEasyJSON

func (v *Notification) UnmarshalEasyJSON(l *jlexer.Lexer)

UnmarshalEasyJSON supports easyjson.Unmarshaler interface

func (*Notification) UnmarshalJSON

func (v *Notification) UnmarshalJSON(data []byte) error

UnmarshalJSON supports json.Unmarshaler interface

type Option

type Option func(*Client) error

Option configurates Client with defined option.

func WithEndpoint

func WithEndpoint(endpoint string) Option

WithEndpoint returns Option to configure FCM Endpoint.

func WithHTTPClient

func WithHTTPClient(httpClient *fasthttp.Client) Option

WithHTTPClient returns Option to configure Fast HTTP Client.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout returns Option to configure HTTP Client timeout.

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"`

	// Device Group HTTP Response
	FailedRegistrationIDs []string `json:"failed_registration_ids"`

	// Topic HTTP response
	MessageID int64  `json:"message_id"`
	Error     string `json:"error"`
}

Response represents the FCM server's response to the application server's sent message.

func (Response) MarshalEasyJSON

func (v Response) MarshalEasyJSON(w *jwriter.Writer)

MarshalEasyJSON supports easyjson.Marshaler interface

func (Response) MarshalJSON

func (v Response) MarshalJSON() ([]byte, error)

MarshalJSON supports json.Marshaler interface

func (*Response) UnmarshalEasyJSON

func (v *Response) UnmarshalEasyJSON(l *jlexer.Lexer)

UnmarshalEasyJSON supports easyjson.Unmarshaler interface

func (*Response) UnmarshalJSON

func (v *Response) UnmarshalJSON(data []byte) error

UnmarshalJSON supports json.Unmarshaler interface

func (*Response) UnmarshalJSON_ORIGINAL

func (r *Response) UnmarshalJSON_ORIGINAL(data []byte) error

UnmarshalJSON implements json.Unmarshaler interface.

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.

func (Result) MarshalEasyJSON

func (v Result) MarshalEasyJSON(w *jwriter.Writer)

MarshalEasyJSON supports easyjson.Marshaler interface

func (Result) MarshalJSON

func (v Result) MarshalJSON() ([]byte, error)

MarshalJSON supports json.Marshaler interface

func (*Result) UnmarshalEasyJSON

func (v *Result) UnmarshalEasyJSON(l *jlexer.Lexer)

UnmarshalEasyJSON supports easyjson.Unmarshaler interface

func (*Result) UnmarshalJSON

func (v *Result) UnmarshalJSON(data []byte) error

UnmarshalJSON supports json.Unmarshaler interface

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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