How do I send push notifications in Go?

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

Go Push Notifications Firebase Cloud Messaging FCM Send Notifications Go