fcm

package module
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2021 License: MIT Imports: 10 Imported by: 0

README

go-fcm

GoDoc Build Status Go Report Card

This project was forked from github.com/edganiukov/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)

Getting Started

To install fcm, use go get:

go get github.com/appleboy/go-fcm

or govendor:

govendor fetch github.com/appleboy/go-fcm

or other tool for vendoring.

Sample Usage

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

package main

import (
	"log"

	"github.com/appleboy/go-fcm"
)

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, err := client.Send(msg)
	if err != nil {
		log.Fatalln(err)
	}

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

Documentation

Overview

Package fcm provides Firebase Cloud Messaging functionality for Golang

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

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, err := client.Send(msg)
	if err != nil {
		log.Fatalln(err)
	}

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

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

	// ErrInvalidApnsCredential for Invalid APNs credentials
	ErrInvalidApnsCredential = errors.New("invalid APNs credentials")
)
View Source
var (
	// ErrInvalidAPIKey occurs if API key is not set.
	ErrInvalidAPIKey = errors.New("client API Key is invalid")
)

Functions

This section is empty.

Types

type AndroidConfig

type AndroidConfig struct {
	// CollapseKey: An identifier of a group of messages that can be
	// collapsed, so that only the last message gets sent when delivery can
	// be resumed. A maximum of 4 different collapse keys is allowed at any
	// given time.
	CollapseKey string `json:"collapseKey,omitempty"`

	// Data: Arbitrary key/value payload. If present, it will override
	// google.firebase.fcm.v1.Message.data.
	Data map[string]string `json:"data,omitempty"`

	// DirectBootOk: If set to true, messages will be allowed to be
	// delivered to the app while the device is in direct boot mode. See
	// Support Direct Boot mode
	// (https://developer.android.com/training/articles/direct-boot).
	DirectBootOk bool `json:"directBootOk,omitempty"`

	// FcmOptions: Options for features provided by the FCM SDK for Android.
	FcmOptions *AndroidFcmOptions `json:"fcmOptions,omitempty"`

	// Notification: Notification to send to android devices.
	Notification *AndroidNotification `json:"notification,omitempty"`

	// Priority: Message priority. Can take "normal" and "high" values. For
	// more information, see Setting the priority of a message
	// (https://goo.gl/GjONJv).
	//
	// Possible values:
	//   "NORMAL" - Default priority for data messages. Normal priority
	// messages won't open network connections on a sleeping device, and
	// their delivery may be delayed to conserve the battery. For less
	// time-sensitive messages, such as notifications of new email or other
	// data to sync, choose normal delivery priority.
	//   "HIGH" - Default priority for notification messages. FCM attempts
	// to deliver high priority messages immediately, allowing the FCM
	// service to wake a sleeping device when possible and open a network
	// connection to your app server. Apps with instant messaging, chat, or
	// voice call alerts, for example, generally need to open a network
	// connection and make sure FCM delivers the message to the device
	// without delay. Set high priority if the message is time-critical and
	// requires the user's immediate interaction, but beware that setting
	// your messages to high priority contributes more to battery drain
	// compared with normal priority messages.
	Priority string `json:"priority,omitempty"`

	// RestrictedPackageName: Package name of the application where the
	// registration token must match in order to receive the message.
	RestrictedPackageName string `json:"restrictedPackageName,omitempty"`

	// Ttl: How long (in seconds) the message should be kept in FCM storage
	// if the device is offline. The maximum time to live supported is 4
	// weeks, and the default value is 4 weeks if not set. Set it to 0 if
	// want to send the message immediately. In JSON format, the Duration
	// type is encoded as a string rather than an object, where the string
	// ends in the suffix "s" (indicating seconds) and is preceded by the
	// number of seconds, with nanoseconds expressed as fractional seconds.
	// For example, 3 seconds with 0 nanoseconds should be encoded in JSON
	// format as "3s", while 3 seconds and 1 nanosecond should be expressed
	// in JSON format as "3.000000001s". The ttl will be rounded down to the
	// nearest second.
	Ttl string `json:"ttl,omitempty"`
}

AndroidConfig : Android specific options for messages sent through FCM connection server (https://goo.gl/4GLdUl).

type AndroidFcmOptions

type AndroidFcmOptions struct {
	// AnalyticsLabel: Label associated with the message's analytics data.
	AnalyticsLabel string `json:"analyticsLabel,omitempty"`
}

AndroidFcmOptions : Options for features provided by the FCM SDK for Android.

type AndroidNotification

type AndroidNotification struct {
	// Body: The notification's body text. If present, it will override
	// google.firebase.fcm.v1.Notification.body.
	Body string `json:"body,omitempty"`

	// BodyLocArgs: Variable string values to be used in place of the format
	// specifiers in body_loc_key to use to localize the body text to the
	// user's current localization. See Formatting and Styling
	// (https://goo.gl/MalYE3) for more information.
	BodyLocArgs []string `json:"bodyLocArgs,omitempty"`

	// BodyLocKey: The key to the body string in the app's string resources
	// to use to localize the body text to the user's current localization.
	// See String Resources (https://goo.gl/NdFZGI) for more information.
	BodyLocKey string `json:"bodyLocKey,omitempty"`

	// ChannelId: The notification's channel id
	// (https://developer.android.com/guide/topics/ui/notifiers/notifications#ManageChannels)
	// (new in Android O). The app must create a channel with this channel
	// ID before any notification with this channel ID is received. If you
	// don't send this channel ID in the request, or if the channel ID
	// provided has not yet been created by the app, FCM uses the channel ID
	// specified in the app manifest.
	ChannelId string `json:"channelId,omitempty"`

	// ClickAction: The action associated with a user click on the
	// notification. If specified, an activity with a matching intent filter
	// is launched when a user clicks on the notification.
	ClickAction string `json:"clickAction,omitempty"`

	// Color: The notification's icon color, expressed in #rrggbb format.
	Color string `json:"color,omitempty"`

	// DefaultLightSettings: If set to true, use the Android framework's
	// default LED light settings for the notification. Default values are
	// specified in config.xml
	// (https://android.googlesource.com/platform/frameworks/base/+/master/core/res/res/values/config.xml).
	// If `default_light_settings` is set to true and `light_settings` is
	// also set, the user-specified `light_settings` is used instead of the
	// default value.
	DefaultLightSettings bool `json:"defaultLightSettings,omitempty"`

	// DefaultSound: If set to true, use the Android framework's default
	// sound for the notification. Default values are specified in
	// config.xml
	// (https://android.googlesource.com/platform/frameworks/base/+/master/core/res/res/values/config.xml).
	DefaultSound bool `json:"defaultSound,omitempty"`

	// DefaultVibrateTimings: If set to true, use the Android framework's
	// default vibrate pattern for the notification. Default values are
	// specified in config.xml
	// (https://android.googlesource.com/platform/frameworks/base/+/master/core/res/res/values/config.xml).
	// If `default_vibrate_timings` is set to true and `vibrate_timings` is
	// also set, the default value is used instead of the user-specified
	// `vibrate_timings`.
	DefaultVibrateTimings bool `json:"defaultVibrateTimings,omitempty"`

	// EventTime: Set the time that the event in the notification occurred.
	// Notifications in the panel are sorted by this time. A point in time
	// is represented using protobuf.Timestamp
	// (https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/Timestamp).
	EventTime string `json:"eventTime,omitempty"`

	// Icon: The notification's icon. Sets the notification icon to myicon
	// for drawable resource myicon. If you don't send this key in the
	// request, FCM displays the launcher icon specified in your app
	// manifest.
	Icon string `json:"icon,omitempty"`

	// Image: Contains the URL of an image that is going to be displayed in
	// a notification. If present, it will override
	// google.firebase.fcm.v1.Notification.image.
	Image string `json:"image,omitempty"`

	// LightSettings: Settings to control the notification's LED blinking
	// rate and color if LED is available on the device. The total blinking
	// time is controlled by the OS.
	LightSettings *LightSettings `json:"lightSettings,omitempty"`

	// LocalOnly: Set whether or not this notification is relevant only to
	// the current device. Some notifications can be bridged to other
	// devices for remote display, such as a Wear OS watch. This hint can be
	// set to recommend this notification not be bridged. See Wear OS guides
	// (https://developer.android.com/training/wearables/notifications/bridger#existing-method-of-preventing-bridging)
	LocalOnly bool `json:"localOnly,omitempty"`

	// NotificationCount: Sets the number of items this notification
	// represents. May be displayed as a badge count for launchers that
	// support badging.See Notification Badge
	// (https://developer.android.com/training/notify-user/badges). For
	// example, this might be useful if you're using just one notification
	// to represent multiple new messages but you want the count here to
	// represent the number of total new messages. If zero or unspecified,
	// systems that support badging use the default, which is to increment a
	// number displayed on the long-press menu each time a new notification
	// arrives.
	NotificationCount int64 `json:"notificationCount,omitempty"`

	// NotificationPriority: Set the relative priority for this
	// notification. Priority is an indication of how much of the user's
	// attention should be consumed by this notification. Low-priority
	// notifications may be hidden from the user in certain situations,
	// while the user might be interrupted for a higher-priority
	// notification. The effect of setting the same priorities may differ
	// slightly on different platforms. Note this priority differs from
	// `AndroidMessagePriority`. This priority is processed by the client
	// after the message has been delivered, whereas AndroidMessagePriority
	// (https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#androidmessagepriority)
	// is an FCM concept that controls when the message is delivered.
	//
	// Possible values:
	//   "PRIORITY_UNSPECIFIED" - If priority is unspecified, notification
	// priority is set to `PRIORITY_DEFAULT`.
	//   "PRIORITY_MIN" - Lowest notification priority. Notifications with
	// this `PRIORITY_MIN` might not be shown to the user except under
	// special circumstances, such as detailed notification logs.
	//   "PRIORITY_LOW" - Lower notification priority. The UI may choose to
	// show the notifications smaller, or at a different position in the
	// list, compared with notifications with `PRIORITY_DEFAULT`.
	//   "PRIORITY_DEFAULT" - Default notification priority. If the
	// application does not prioritize its own notifications, use this value
	// for all notifications.
	//   "PRIORITY_HIGH" - Higher notification priority. Use this for more
	// important notifications or alerts. The UI may choose to show these
	// notifications larger, or at a different position in the notification
	// lists, compared with notifications with `PRIORITY_DEFAULT`.
	//   "PRIORITY_MAX" - Highest notification priority. Use this for the
	// application's most important items that require the user's prompt
	// attention or input.
	NotificationPriority string `json:"notificationPriority,omitempty"`

	// Sound: The sound to play when the device receives the notification.
	// Supports "default" or the filename of a sound resource bundled in the
	// app. Sound files must reside in /res/raw/.
	Sound string `json:"sound,omitempty"`

	// Sticky: When set to false or unset, the notification is automatically
	// dismissed when the user clicks it in the panel. When set to true, the
	// notification persists even when the user clicks it.
	Sticky bool `json:"sticky,omitempty"`

	// Tag: Identifier used to replace existing notifications in the
	// notification drawer. If not specified, each request creates a new
	// notification. If specified and a notification with the same tag is
	// already being shown, the new notification replaces the existing one
	// in the notification drawer.
	Tag string `json:"tag,omitempty"`

	// Ticker: Sets the "ticker" text, which is sent to accessibility
	// services. Prior to API level 21 (`Lollipop`), sets the text that is
	// displayed in the status bar when the notification first arrives.
	Ticker string `json:"ticker,omitempty"`

	// Title: The notification's title. If present, it will override
	// google.firebase.fcm.v1.Notification.title.
	Title string `json:"title,omitempty"`

	// TitleLocArgs: Variable string values to be used in place of the
	// format specifiers in title_loc_key to use to localize the title text
	// to the user's current localization. See Formatting and Styling
	// (https://goo.gl/MalYE3) for more information.
	TitleLocArgs []string `json:"titleLocArgs,omitempty"`

	// TitleLocKey: The key to the title string in the app's string
	// resources to use to localize the title text to the user's current
	// localization. See String Resources (https://goo.gl/NdFZGI) for more
	// information.
	TitleLocKey string `json:"titleLocKey,omitempty"`

	// VibrateTimings: Set the vibration pattern to use. Pass in an array of
	// protobuf.Duration
	// (https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Duration)
	// to turn on or off the vibrator. The first value indicates the
	// `Duration` to wait before turning the vibrator on. The next value
	// indicates the `Duration` to keep the vibrator on. Subsequent values
	// alternate between `Duration` to turn the vibrator off and to turn the
	// vibrator on. If `vibrate_timings` is set and
	// `default_vibrate_timings` is set to `true`, the default value is used
	// instead of the user-specified `vibrate_timings`.
	VibrateTimings []string `json:"vibrateTimings,omitempty"`

	// Visibility: Set the Notification.visibility
	// (https://developer.android.com/reference/android/app/Notification.html#visibility)
	// of the notification.
	//
	// Possible values:
	//   "VISIBILITY_UNSPECIFIED" - If unspecified, default to
	// `Visibility.PRIVATE`.
	//   "PRIVATE" - Show this notification on all lockscreens, but conceal
	// sensitive or private information on secure lockscreens.
	//   "PUBLIC" - Show this notification in its entirety on all
	// lockscreens.
	//   "SECRET" - Do not reveal any part of this notification on a secure
	// lockscreen.
	Visibility string `json:"visibility,omitempty"`
}

AndroidNotification : Notification to send to android devices.

type ApnsConfig

type ApnsConfig struct {
	// FcmOptions: Options for features provided by the FCM SDK for iOS.
	FcmOptions *ApnsFcmOptions `json:"fcmOptions,omitempty"`

	// Headers: HTTP request headers defined in Apple Push Notification
	// Service. Refer to APNs request headers
	// (https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/sending_notification_requests_to_apns)
	// for supported headers, e.g. "apns-priority": "10".
	Headers map[string]string `json:"headers,omitempty"`

	// Payload: APNs payload as a JSON object, including both `aps`
	// dictionary and custom payload. See Payload Key Reference
	// (https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/generating_a_remote_notification).
	// If present, it overrides google.firebase.fcm.v1.Notification.title
	// and google.firebase.fcm.v1.Notification.body.
	Payload googleapi.RawMessage `json:"payload,omitempty"`
}

ApnsConfig : Apple Push Notification Service (https://goo.gl/MXRTPa) specific options.

type ApnsFcmOptions

type ApnsFcmOptions struct {
	// AnalyticsLabel: Label associated with the message's analytics data.
	AnalyticsLabel string `json:"analyticsLabel,omitempty"`

	// Image: Contains the URL of an image that is going to be displayed in
	// a notification. If present, it will override
	// google.firebase.fcm.v1.Notification.image.
	Image string `json:"image,omitempty"`
}

ApnsFcmOptions : Options for features provided by the FCM SDK for iOS.

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, 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) SendWithContext

func (c *Client) SendWithContext(ctx context.Context, msg *Message) (*Response, error)

SendWithContext 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"). Behaves just like regular send, but uses external context.

func (*Client) SendWithRetry

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

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

func (*Client) SendWithRetryWithContext

func (c *Client) SendWithRetryWithContext(ctx context.Context, msg *Message, retryAttempts int) (*Response, error)

SendWithRetryWithContext sends a message to the FCM server with defined number of retrying in case of temporary error. Behaves just like regular SendWithRetry, but uses external context.

type Color

type Color struct {
	// Alpha: The fraction of this color that should be applied to the
	// pixel. That is, the final pixel color is defined by the equation:
	// `pixel color = alpha * (this color) + (1.0 - alpha) * (background
	// color)` This means that a value of 1.0 corresponds to a solid color,
	// whereas a value of 0.0 corresponds to a completely transparent color.
	// This uses a wrapper message rather than a simple float scalar so that
	// it is possible to distinguish between a default value and the value
	// being unset. If omitted, this color object is rendered as a solid
	// color (as if the alpha value had been explicitly given a value of
	// 1.0).
	Alpha float64 `json:"alpha,omitempty"`

	// Blue: The amount of blue in the color as a value in the interval [0,
	// 1].
	Blue float64 `json:"blue,omitempty"`

	// Green: The amount of green in the color as a value in the interval
	// [0, 1].
	Green float64 `json:"green,omitempty"`

	// Red: The amount of red in the color as a value in the interval [0,
	// 1].
	Red float64 `json:"red,omitempty"`
}

type FcmOptions

type FcmOptions struct {
	// AnalyticsLabel: Label associated with the message's analytics data.
	AnalyticsLabel string `json:"analyticsLabel,omitempty"`
}

FcmOptions : Platform independent options for features provided by the FCM SDKs.

type LightSettings

type LightSettings struct {
	// Color: Required. Set `color` of the LED with google.type.Color
	// (https://github.com/googleapis/googleapis/blob/master/google/type/color.proto).
	Color *Color `json:"color,omitempty"`

	// LightOffDuration: Required. Along with `light_on_duration `, define
	// the blink rate of LED flashes. Resolution defined by proto.Duration
	// (https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Duration)
	LightOffDuration string `json:"lightOffDuration,omitempty"`

	// LightOnDuration: Required. Along with `light_off_duration`, define
	// the blink rate of LED flashes. Resolution defined by proto.Duration
	// (https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Duration)
	LightOnDuration string `json:"lightOnDuration,omitempty"`
}

LightSettings : Settings to control notification LED.

type Message

type Message struct {
	RegistrationIDs []string `json:"registration_ids"`

	// Android: Input only. Android specific options for messages sent
	// through FCM connection server (https://goo.gl/4GLdUl).
	Android *AndroidConfig `json:"android,omitempty"`

	// Apns: Input only. Apple Push Notification Service
	// (https://goo.gl/MXRTPa) specific options.
	Apns *ApnsConfig `json:"apns,omitempty"`

	// Condition: Condition to send a message to, e.g. "'foo' in topics &&
	// 'bar' in topics".
	Condition string `json:"condition,omitempty"`

	// Data: Input only. Arbitrary key/value payload. The key should not be
	// a reserved word ("from", "message_type", or any word starting with
	// "google" or "gcm").
	Data map[string]string `json:"data,omitempty"`

	// FcmOptions: Input only. Template for FCM SDK feature options to use
	// across all platforms.
	FcmOptions *FcmOptions `json:"fcmOptions,omitempty"`

	// Name: Output Only. The identifier of the message sent, in the format
	// of `projects/*/messages/{message_id}`.
	Name string `json:"name,omitempty"`

	// Notification: Input only. Basic notification template to use across
	// all platforms.
	Notification *Notification `json:"notification,omitempty"`

	// Token: Registration token to send a message to.
	Token string `json:"token,omitempty"`

	// Topic: Topic name to send a message to, e.g. "weather". Note:
	// "/topics/" prefix should not be provided.
	Topic string `json:"topic,omitempty"`

	// Webpush: Input only. Webpush protocol
	// (https://tools.ietf.org/html/rfc8030) options.
	Webpush *WebpushConfig `json:"webpush,omitempty"`

	TimeToLive *uint `json:"time_to_live,omitempty"`
}

func (*Message) Validate

func (msg *Message) Validate() error

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

type Notification

type Notification struct {
	// Body: The notification's body text.
	Body string `json:"body,omitempty"`

	// Image: Contains the URL of an image that is going to be downloaded on
	// the device and displayed in a notification. JPEG, PNG, BMP have full
	// support across platforms. Animated GIF and video only work on iOS.
	// WebP and HEIF have varying levels of support across platforms and
	// platform versions. Android has 1MB image size limit. Quota usage and
	// implications/costs for hosting image on Firebase Storage:
	// https://firebase.google.com/pricing
	Image string `json:"image,omitempty"`

	// Title: The notification's title.
	Title string `json:"title,omitempty"`
}

Notification : Basic notification template to use across all platforms.

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 *http.Client) Option

WithHTTPClient returns Option to configure 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             error `json:"error"`
	ErrorResponseCode string
}

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

func (*Response) UnmarshalJSON

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

UnmarshalJSON implements json.Unmarshaler interface.

type Result

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

Result represents the status of a processed message.

func (*Result) UnmarshalJSON

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

UnmarshalJSON implements json.Unmarshaler interface.

func (Result) Unregistered

func (r Result) Unregistered() bool

Unregistered checks if the device token is unregistered, according to response from FCM server. Useful to determine if app is uninstalled.

type WebpushConfig

type WebpushConfig struct {
	// Data: Arbitrary key/value payload. If present, it will override
	// google.firebase.fcm.v1.Message.data.
	Data map[string]string `json:"data,omitempty"`

	// FcmOptions: Options for features provided by the FCM SDK for Web.
	FcmOptions *WebpushFcmOptions `json:"fcmOptions,omitempty"`

	// Headers: HTTP headers defined in webpush protocol. Refer to Webpush
	// protocol (https://tools.ietf.org/html/rfc8030#section-5) for
	// supported headers, e.g. "TTL": "15".
	Headers map[string]string `json:"headers,omitempty"`

	// Notification: Web Notification options as a JSON object. Supports
	// Notification instance properties as defined in Web Notification API
	// (https://developer.mozilla.org/en-US/docs/Web/API/Notification). If
	// present, "title" and "body" fields override
	// [google.firebase.fcm.v1.Notification.title] and
	// [google.firebase.fcm.v1.Notification.body].
	Notification googleapi.RawMessage `json:"notification,omitempty"`
}

WebpushConfig : Webpush protocol (https://tools.ietf.org/html/rfc8030) options.

type WebpushFcmOptions

type WebpushFcmOptions struct {
	// AnalyticsLabel: Label associated with the message's analytics data.
	AnalyticsLabel string `json:"analyticsLabel,omitempty"`

	// Link: The link to open when the user clicks on the notification. For
	// all URL values, HTTPS is required.
	Link string `json:"link,omitempty"`
}

WebpushFcmOptions : Options for features provided by the FCM SDK for Web.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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