iTranslated by AI
Sending Web Push Notifications with Firebase Cloud Messaging in Go
Overview
In this article, I will introduce an example of sending Web push notifications from Go as follows.
What is Firebase Cloud Messaging?
By using Firebase Cloud Messaging, you can send Web push notifications, which are also used in services like Instagram and YouTube.
Flow for sending Push notifications
Issue a token on the client → Save the token on the server side → Issue a message from the server side to Firebase
Client Registration with React
This section explains how to issue a Firebase Cloud Messaging token on the client side using firebase v9 (@firebase/messaging@0.9.16).
On the client side, use the following code to generate a Firebase Cloud Messaging token for each client.
import { getMessaging, getToken } from "firebase/messaging"
const app = initializeApp(firebaseConfig)
const messaging = getMessaging(app)
const fcm_token = await getToken(messaging, {
vapidKey: "****",
})
console.log(fcm_token)
Subsequently, the token is saved on the server side using some method (such as an API) from the client. The tokens saved here must be updated at appropriate times.
This article proceeds on the assumption that the token mentioned above has already been saved on the server side.
Sending Notifications with Go
Here is a sample for sending notifications to multiple devices (users) at once.
- Initializing Firebase
import (
firebase "firebase.google.com/go"
)
app, err := firebase.NewApp(context.TODO(), &firebase.Config{})
if err != nil {
log.Print(err)
}
- Initializing Cloud Messaging
client, err := app.Messaging(context.TODO())
if err != nil {
log.Print(err)
}
- Creating the message
By setting an https link in WebpushFcmOptions.Link, you can specify the link to transition to when the Push notification is clicked.
In Tokens, set the Firebase Cloud Messaging tokens generated by each client as a string array.
message := &messaging.MulticastMessage{
Tokens: tokens,
Notification: notification,
Webpush: &messaging.WebpushConfig{
FcmOptions: &messaging.WebpushFcmOptions{
Link: "https://example.com",
},
},
}
- Sending the message
br, err := client.SendMulticast(context.TODO(), message)
if err != nil {
log.Print(err)
}
Discussion