以下是一个使用Golang发送FCM推送消息的示例代码:
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
func main() {
fcmServerKey := "YOUR_FCM_SERVER_KEY"
message := map[string]interface{}{
"to": "/topics/mytopic",
"data": map[string]string{
"title": "Hello",
"message": "This is a test notification",
},
}
payload, err := json.Marshal(message)
if err != nil {
fmt.Println("Failed to marshal message:", err)
return
}
request, err := http.NewRequest("POST", "https://fcm.googleapis.com/fcm/send", bytes.NewBuffer(payload))
if err != nil {
fmt.Println("Failed to create request:", err)
return
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Authorization", fmt.Sprintf("key=%s", fcmServerKey))
client := &http.Client{}
response, err := client.Do(request)
if err != nil {
fmt.Println("Failed to send request:", err)
return
}
defer response.Body.Close()
fmt.Println("Response Status:", response.Status)
fmt.Println("Response Body:")
buf := new(bytes.Buffer)
buf.ReadFrom(response.Body)
fmt.Println(buf.String())
}
请注意,您需要将YOUR_FCM_SERVER_KEY
替换为您自己的FCM服务器密钥。此代码使用HTTP请求向FCM发送JSON格式的推送消息。
内容由零声教学AI助手提供,问题来源于学员提问