fcm

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Feb 5, 2026 License: MIT Imports: 17 Imported by: 0

README

fcm

build-img pkg-img reportcard-img coverage-img version-img

Firebase Cloud Messaging client in Go. A lightweight alternative to firebase.google.com/go/v4.

Rationale

firebase.google.com/go/v4 has tremendous dependencies, resulting in nearly 1,000,000 lines of code (as of v4.18.0). There are many features in the original library, but sending a push notification via FCM requires just a single HTTP request. That’s exactly what this library provides.

Features

Install

Go version 1.24+

go get github.com/cristalhq/fcm

Example

Build new token:

creds := []byte("...") // your JSON file from Firebase project settings

cfg := fcm.Config{
	ProjectID:   "example-android-app",
	Credentials: creds,
}

client, err := fcm.NewClient(cfg)
if err != nil {
	panic(err)
}

deviceToken := "..."

msg := &fcm.Message{
	Data: map[string]string{
		"force_show": "1",
	},
	Notification: &fcm.Notification{
		Title: "Test",
		Body:  "Push from https://github.com/cristalhq/fcm",
	},
	Token: deviceToken,
}

pushID, err := client.Send(ctx, msg)
if err != nil {
	panic(err)
}

fmt.Printf("pushID: %s\n", pushID)

Also see examples: example_test.go.

Documentation

See these docs.

License

MIT License.

Documentation

Overview

Example
package main

import (
	"context"

	_ "embed"
	"github.com/cristalhq/fcm"
)

func main() {
	ctx := context.Background()

	creds := []byte("...") // your JSON file from Firebase project settings

	cfg := fcm.Config{
		ProjectID:   "example-android-app",
		Credentials: creds,
	}

	client, err := fcm.NewClient(cfg)
	if err != nil {
		panic(err)
	}

	deviceToken := "..."

	msg := &fcm.Message{
		Data: map[string]string{
			"force_show": "1",
		},
		Notification: &fcm.Notification{
			Title: "Test",
			Body:  "Push from https://github.com/cristalhq/fcm",
		},
		Token: deviceToken,
	}

	response, err := client.Send(ctx, msg)
	if err != nil {
		// skipping error handling for example test
		panic(err)
	}

	_ = response.Name // notification ID
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type APNSConfig added in v0.3.0

type APNSConfig struct {
	Headers           map[string]string `json:"headers,omitempty"`
	Payload           *APNSPayload      `json:"payload,omitempty"`
	FCMOptions        *APNSFCMOptions   `json:"fcm_options,omitempty"`
	LiveActivityToken string            `json:"live_activity_token,omitempty"`
}

APNSConfig contains messaging options specific to the Apple Push Notification Service (APNS). https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#apnsconfig

See https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html

type APNSFCMOptions added in v0.3.0

type APNSFCMOptions struct {
	AnalyticsLabel string `json:"analytics_label,omitempty"`
	ImageURL       string `json:"image,omitempty"`
}

APNSFCMOptions contains additional options for features provided by the FCM Aps SDK.

See https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#apnsfcmoptions

type APNSPayload added in v0.3.0

type APNSPayload struct {
	Aps        *Aps           `json:"aps,omitempty"`
	CustomData map[string]any `json:"-"`
}

APNSPayload is the payload that can be included in an APNS message.

The payload mainly consists of the aps dictionary. Additionally it may contain arbitrary key-values pairs as custom data fields.

See https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/PayloadKeyReference.html

func (*APNSPayload) MarshalJSON added in v0.3.0

func (p *APNSPayload) MarshalJSON() ([]byte, error)

func (*APNSPayload) UnmarshalJSON added in v0.3.0

func (p *APNSPayload) UnmarshalJSON(b []byte) error

type AndroidConfig added in v0.3.0

type AndroidConfig struct {
	CollapseKey           string               `json:"collapse_key,omitempty"`
	Priority              string               `json:"priority,omitempty"` // one of "normal" or "high"
	TTL                   *time.Duration       `json:"-"`
	RestrictedPackageName string               `json:"restricted_package_name,omitempty"`
	Data                  map[string]string    `json:"data,omitempty"` // if set, overrides [Message.Data] field.
	Notification          *AndroidNotification `json:"notification,omitempty"`
	FCMOptions            *AndroidFCMOptions   `json:"fcm_options,omitempty"`
	DirectBootOK          bool                 `json:"direct_boot_ok,omitempty"`
}

AndroidConfig contains messaging options specific to the Android platform.

See https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#androidconfig

func (*AndroidConfig) MarshalJSON added in v0.3.0

func (a *AndroidConfig) MarshalJSON() ([]byte, error)

func (*AndroidConfig) UnmarshalJSON added in v0.3.0

func (a *AndroidConfig) UnmarshalJSON(b []byte) error

type AndroidFCMOptions added in v0.3.0

type AndroidFCMOptions struct {
	AnalyticsLabel string `json:"analytics_label,omitempty"`
}

AndroidFCMOptions contains additional options for features provided by the FCM Android SDK.

See https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#androidfcmoptions

type AndroidNotification added in v0.3.0

type AndroidNotification struct {
	Title                 string                        `json:"title,omitempty"` // if set, overrides [Notification.Title] field.
	Body                  string                        `json:"body,omitempty"`  // if set, overrides [Notification.Body] field.
	Icon                  string                        `json:"icon,omitempty"`
	Color                 string                        `json:"color,omitempty"` // #RRGGBB format
	Sound                 string                        `json:"sound,omitempty"`
	Tag                   string                        `json:"tag,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"`
	ChannelID             string                        `json:"channel_id,omitempty"`
	Ticker                string                        `json:"ticker,omitempty"`
	Sticky                bool                          `json:"sticky,omitempty"`
	EventTimestamp        *time.Time                    `json:"-"`
	LocalOnly             bool                          `json:"local_only,omitempty"`
	Priority              AndroidNotificationPriority   `json:"-"`
	DefaultSound          bool                          `json:"default_sound,omitempty"`
	DefaultVibrateTimings bool                          `json:"default_vibrate_timings,omitempty"`
	DefaultLightSettings  bool                          `json:"default_light_settings,omitempty"`
	VibrateTimingMillis   []int64                       `json:"-"`
	Visibility            AndroidNotificationVisibility `json:"-"`
	NotificationCount     *int                          `json:"notification_count,omitempty"`
	LightSettings         *LightSettings                `json:"light_settings,omitempty"`
	ImageURL              string                        `json:"image,omitempty"`
	Proxy                 AndroidNotificationProxy      `json:"-"`
}

AndroidNotification is a notification to send to Android devices.

See https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#androidnotification

func (*AndroidNotification) MarshalJSON added in v0.3.0

func (a *AndroidNotification) MarshalJSON() ([]byte, error)

func (*AndroidNotification) UnmarshalJSON added in v0.3.0

func (a *AndroidNotification) UnmarshalJSON(b []byte) error

type AndroidNotificationPriority added in v0.3.0

type AndroidNotificationPriority int

AndroidNotificationPriority represents the priority levels of a notification.

const (

	// PriorityMin is the lowest notification priority.
	// Notifications with this priority might not be shown to the user except under special circumstances, such as detailed notification logs.
	PriorityMin AndroidNotificationPriority = 1

	// PriorityLow is a lower notification priority.
	// The UI may choose to show the notifications smaller, or at a different position in the list, compared with notifications with PriorityDefault.
	PriorityLow AndroidNotificationPriority = 2

	// PriorityDefault is the default notification priority.
	// If the application does not prioritize its own notifications, use this value for all notifications.
	PriorityDefault AndroidNotificationPriority = 3

	// PriorityHigh is a 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 PriorityDefault.
	PriorityHigh AndroidNotificationPriority = 4

	// PriorityMax is the highest notification priority.
	// Use this for the application's most important items that require the user's prompt attention or input.
	PriorityMax AndroidNotificationPriority = 5
)

type AndroidNotificationProxy added in v0.3.0

type AndroidNotificationProxy int

AndroidNotificationProxy to control when a notification may be proxied.

const (

	// ProxyAllow tries to proxy this notification.
	ProxyAllow AndroidNotificationProxy = 1

	// ProxyDeny does not proxy this notification.
	ProxyDeny AndroidNotificationProxy = 2

	// ProxyIfPriorityLowered only tries to proxy this notification if its AndroidConfig's Priority was lowered from high to normal on the device.
	ProxyIfPriorityLowered AndroidNotificationProxy = 3
)

type AndroidNotificationVisibility added in v0.3.0

type AndroidNotificationVisibility int

AndroidNotificationVisibility represents the different visibility levels of a notification.

const (

	// VisibilityPrivate shows this notification on all lockscreens, but conceal sensitive or private information on secure lockscreens.
	VisibilityPrivate AndroidNotificationVisibility = 1

	// VisibilityPublic shows this notification in its entirety on all lockscreens.
	VisibilityPublic AndroidNotificationVisibility = 2

	// VisibilitySecret does not reveal any part of this notification on a secure lockscreen.
	VisibilitySecret AndroidNotificationVisibility = 3
)

type Aps added in v0.3.0

type Aps struct {
	AlertString      string         `json:"-"`
	Alert            *ApsAlert      `json:"-"`
	Badge            *int           `json:"badge,omitempty"`
	Sound            string         `json:"-"`
	CriticalSound    *CriticalSound `json:"-"`
	ContentAvailable bool           `json:"-"`
	MutableContent   bool           `json:"-"`
	Category         string         `json:"category,omitempty"`
	ThreadID         string         `json:"thread-id,omitempty"`
	CustomData       map[string]any `json:"-"`
}

Aps represents the aps dictionary that may be included in an APNSPayload.

Alert may be specified as a string (via the AlertString field), or as a struct (via the Alert field).

func (*Aps) MarshalJSON added in v0.3.0

func (a *Aps) MarshalJSON() ([]byte, error)

func (*Aps) UnmarshalJSON added in v0.3.0

func (a *Aps) UnmarshalJSON(b []byte) error

type ApsAlert added in v0.3.0

type ApsAlert struct {
	Title           string   `json:"title,omitempty"` // if set, overrides [Notification.Title] field.
	SubTitle        string   `json:"subtitle,omitempty"`
	Body            string   `json:"body,omitempty"` // if set, overrides [Notification.Body] field.
	LocKey          string   `json:"loc-key,omitempty"`
	LocArgs         []string `json:"loc-args,omitempty"`
	TitleLocKey     string   `json:"title-loc-key,omitempty"`
	TitleLocArgs    []string `json:"title-loc-args,omitempty"`
	SubTitleLocKey  string   `json:"subtitle-loc-key,omitempty"`
	SubTitleLocArgs []string `json:"subtitle-loc-args,omitempty"`
	ActionLocKey    string   `json:"action-loc-key,omitempty"`
	LaunchImage     string   `json:"launch-image,omitempty"`
}

ApsAlert is the alert payload that can be included in an Aps.

See https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/PayloadKeyReference.html

type Client

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

Client for the Firebase Cloud Messaging (FCM) service.

func NewClient

func NewClient(cfg Config) (*Client, error)

NewClient creates a new instance of the Firebase Cloud Messaging Client.

func (*Client) Send

func (c *Client) Send(ctx context.Context, message *Message) (*Response, error)

Send a Message to Firebase Cloud Messaging (FCM).

The Message must specify exactly one of Token, Topic and Condition fields. FCM will customize the message for each target platform based on the arguments specified in the Message.

type Config

type Config struct {
	Client      httpClient
	Credentials []byte
	ProjectID   string
	Endpoint    string
}

type CriticalSound added in v0.3.0

type CriticalSound struct {
	Critical bool    `json:"-"`
	Name     string  `json:"name,omitempty"`
	Volume   float64 `json:"volume,omitempty"`
}

CriticalSound is the sound payload that can be included in an Aps.

func (*CriticalSound) MarshalJSON added in v0.3.0

func (cs *CriticalSound) MarshalJSON() ([]byte, error)

func (*CriticalSound) UnmarshalJSON added in v0.3.0

func (cs *CriticalSound) UnmarshalJSON(b []byte) error

type FCMOptions added in v0.3.0

type FCMOptions struct {
	AnalyticsLabel string `json:"analytics_label,omitempty"`
}

FCMOptions contains additional options to use across all platforms.

See https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#fcmoptions

type LightSettings added in v0.3.0

type LightSettings struct {
	Color                  string
	LightOnDurationMillis  int64
	LightOffDurationMillis int64
}

LightSettings to control notification LED.

func (*LightSettings) MarshalJSON added in v0.3.0

func (l *LightSettings) MarshalJSON() ([]byte, error)

func (*LightSettings) UnmarshalJSON added in v0.3.0

func (l *LightSettings) UnmarshalJSON(b []byte) error

type Message

type Message struct {
	Data         map[string]string `json:"data,omitempty"`
	Notification *Notification     `json:"notification,omitempty"`
	Android      *AndroidConfig    `json:"android,omitempty"`
	Webpush      *WebpushConfig    `json:"webpush,omitempty"`
	APNS         *APNSConfig       `json:"apns,omitempty"`
	FCMOptions   *FCMOptions       `json:"fcm_options,omitempty"`

	Token     string `json:"token,omitempty"`
	Topic     string `json:"-"`
	Condition string `json:"condition,omitempty"`
}

Message to be sent via Firebase Cloud Messaging (FCM). A Message must specify exactly one of Token, Topic or Condition fields.

See https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages

func (Message) IsValid

func (m Message) IsValid() error

func (*Message) MarshalJSON

func (m *Message) MarshalJSON() ([]byte, error)

func (*Message) UnmarshalJSON

func (m *Message) UnmarshalJSON(b []byte) error

type Notification

type Notification struct {
	Title    string `json:"title,omitempty"`
	Body     string `json:"body,omitempty"`
	ImageURL string `json:"image,omitempty"`
}

Notification is the basic notification template to use across all platforms.

See https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#notification

type Response added in v0.4.0

type Response struct {
	Name string `json:"name"`
}

type WebpushConfig added in v0.3.0

type WebpushConfig struct {
	Headers      map[string]string    `json:"headers,omitempty"`
	Data         map[string]string    `json:"data,omitempty"`
	Notification *WebpushNotification `json:"notification,omitempty"`
	FCMOptions   *WebpushFCMOptions   `json:"fcm_options,omitempty"`
}

WebpushConfig contains messaging options specific to the WebPush protocol. https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#webpushconfig

See https://tools.ietf.org/html/rfc8030#section-5

type WebpushFCMOptions added in v0.3.0

type WebpushFCMOptions struct {
	Link string `json:"link,omitempty"`
}

WebpushFCMOptions contains additional options for features provided by the FCM web SDK.

See https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#webpushfcmoptions

type WebpushNotification added in v0.3.0

type WebpushNotification struct {
	Actions            []*WebpushNotificationAction `json:"actions,omitempty"`
	Title              string                       `json:"title,omitempty"` // if set, overrides [Notification.Title] field.
	Body               string                       `json:"body,omitempty"`  // if set, overrides [Notification.Body] field.
	Icon               string                       `json:"icon,omitempty"`
	Badge              string                       `json:"badge,omitempty"`
	Direction          string                       `json:"dir,omitempty"` // one of 'ltr' or 'rtl'
	Data               any                          `json:"data,omitempty"`
	Image              string                       `json:"image,omitempty"`
	Language           string                       `json:"lang,omitempty"`
	Renotify           bool                         `json:"renotify,omitempty"`
	RequireInteraction bool                         `json:"requireInteraction,omitempty"`
	Silent             bool                         `json:"silent,omitempty"`
	Tag                string                       `json:"tag,omitempty"`
	TimestampMillis    *int64                       `json:"timestamp,omitempty"`
	Vibrate            []int                        `json:"vibrate,omitempty"`
	CustomData         map[string]any
}

WebpushNotification is a notification to send via WebPush protocol.

See https://developer.mozilla.org/en-US/docs/Web/API/notification/Notification

func (*WebpushNotification) MarshalJSON added in v0.3.0

func (n *WebpushNotification) MarshalJSON() ([]byte, error)

func (*WebpushNotification) UnmarshalJSON added in v0.3.0

func (n *WebpushNotification) UnmarshalJSON(b []byte) error

type WebpushNotificationAction added in v0.3.0

type WebpushNotificationAction struct {
	Action string `json:"action,omitempty"`
	Title  string `json:"title,omitempty"`
	Icon   string `json:"icon,omitempty"`
}

WebpushNotificationAction represents an action that can be performed upon receiving a WebPush notification.

Jump to

Keyboard shortcuts

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