Sending push notifications in Go can be achieved using various libraries and services. One popular and simple way to do so is by using Firebase Cloud Messaging (FCM). FCM allows you to send messages to client applications running on iOS, Android, and the web.
Below is an example of how to implement FCM in your Go application to send push notifications:
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
const (
serverKey = "YOUR_SERVER_KEY"
fcmURL = "https://fcm.googleapis.com/fcm/send"
)
type Message struct {
To string `json:"to"`
Data struct {
Title string `json:"title"`
Body string `json:"body"`
} `json:"data"`
}
func sendNotification(to string, title string, body string) error {
msg := Message{}
msg.To = to
msg.Data.Title = title
msg.Data.Body = body
jsonMsg, err := json.Marshal(msg)
if err != nil {
return err
}
req, err := http.NewRequest("POST", fcmURL, bytes.NewBuffer(jsonMsg))
if err != nil {
return err
}
req.Header.Set("Authorization", "key="+serverKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
_, err = client.Do(req)
return err
}
func main() {
err := sendNotification("DEVICE_TOKEN", "Hello", "This is a push notification")
if err != nil {
fmt.Println("Error sending notification:", err)
} else {
fmt.Println("Notification sent successfully!")
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?