网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
- 配置 Firebase 身份验证密钥
所需软件包:
firebase.google.com/go
firebase.google.com/go/messaging
使用加密格式的敏感内容总是更好。为了达到这个目的,我将服务帐户密钥以 base64 格式存储为环境变量。
在这里,FIREBASE_AUTH_KEY 包含一个 base64 编码的服务帐户密钥。
首先,让我们解码服务帐户密钥。
func getDecodedFireBaseKey() ([]byte, error) {
fireBaseAuthKey := os.Getenv("FIREBASE_AUTH_KEY")
decodedKey, err := base64.StdEncoding.DecodeString(fireBaseAuthKey)
if err != nil {
return nil, err
}
return decodedKey, nil
}
上述方法将返回解码后的服务帐户密钥,该密钥将在下一步中使用。
使用以下代码检索解码的密钥并初始化 firebase 应用程序。
decodedKey, err := getDecodedFireBaseKey()
if err != nil {
return err
}
opts := []option.ClientOption{option.WithCredentialsJSON(decodedKey)}
// Initialize firebase app
app, err := firebase.NewApp(context.Background(), nil, opts...)
if err != nil {
log.Debug("Error in initializing firebase app: %s", err)
return err
}
3.初始化firebase客户端
创建fcmClient用于消息传递(推送通知)。
fcmClient, err := app.Messaging(context.Background())
if err != nil {
return err
}
最后,让我们编写一个发送通知的代码。
4.向单个设备发送推送通知
response, err := fcmClient.Send(context.Background(), &messaging.Message{
Notification: &messaging.Notification{
Title: "Congratulations!!",
Body: "You have just implement push notification",
},
Token: "sample-device-token", // it's a single device token
})
if err != nil {
return err
}
上面的代码将向单个设备发送推送通知。
- 向多个设备发送推送通知
如果您想通知多个设备,请考虑一个场景。这与我们向单个设备发送推送通知几乎相同,只需将 fcmClient 的 Send() 方法替换为 SendMulticast() 即可。
response, err := fcmClient.SendMulticast(context.Background(), &messaging.MulticastMessage{
Notification: &messaging.Notification{
Title: "Congratulations!!",
Body: "You have just implement push notification",
![img](https://img-blog.csdnimg.cn/img_convert/33d22d1f634120a5cc53cc49d5d85917.png)
![img](https://img-blog.csdnimg.cn/img_convert/a914d5990c4f6ac75454cd276cda490c.png)
![img](https://img-blog.csdnimg.cn/img_convert/e3e9c9972a1179a51dd3f0f850f3bceb.png)
**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上Go语言开发知识点,真正体系化!**
**由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**
**[如果你需要这些资料,可以戳这里获取](https://bbs.csdn.net/topics/618658159)**
*由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**
**[如果你需要这些资料,可以戳这里获取](https://bbs.csdn.net/topics/618658159)**