go-app 通知系统完全指南:从本地通知到 Web 推送通知的实战实现
go-app 通知系统完全指南:从本地通知到 Web 推送通知的实战实现
本篇技术指南基于 go-app 官方文档中关于通知(Notifications)的全部章节,系统讲解如何在 WebAssembly 前端应用中实现浏览器通知功能。你将掌握基于 app.Context 的通知服务 API 的使用方法(权限查询、权限请求、本地通知展示),以及基于 VAPID 协议与 Service Worker 的完整 Web 推送通知链路(订阅获取、服务端注册、推送发送与点击导航),并了解底层源码实现与官方文档站点的真实运行示例。
通知功能概览与前置条件
go-app 的通知功能分为两个层次:
- 本地通知(Local Notifications):由运行中的应用自身通过
Context.Notifications().New()创建并显示的通知,应用必须在浏览器中处于运行状态。 - 推送通知(Push Notifications):由远程服务器发送的通知,无论应用处于运行状态还是已关闭都可以显示,但需要向推送服务完成订阅注册。
两种通知都遵循浏览器 Web Notifications API 与 Push API 的权限模型:显示任何通知之前,必须先获得用户的明确授权。所有相关 API 都通过 Context.Notifications() 访问,该方法的实现在 pkg/app/context.go:
// Notifications accesses the notifications service.
func (ctx Context) Notifications() NotificationService {
return NotificationService{}
}
通知权限模型:四种状态
通知权限由 app.NotificationPermission 类型表示,其定义与取值位于 pkg/app/notification.go:
// NotificationPermission represents permission levels for displaying
// notifications to users.
type NotificationPermission string
const (
// NotificationDefault indicates the user's choice for notifications is
// unknown, prompting the browser to treat it as "denied".
NotificationDefault NotificationPermission = "default"
// NotificationGranted means the user has allowed notifications.
NotificationGranted NotificationPermission = "granted"
// NotificationDenied means the user has declined notifications.
NotificationDenied NotificationPermission = "denied"
// NotificationNotSupported indicates that the browser doesn't support
// notifications.
NotificationNotSupported NotificationPermission = "unsupported"
)
四种取值说明:
| 权限值 | 含义 | 触发场景 |
|---|---|---|
app.NotificationDefault |
用户尚未做出选择,浏览器按"拒绝"处理 | 首次访问,尚未弹出授权询问 |
app.NotificationGranted |
用户已允许显示通知 | 授权成功或历史上已授权 |
app.NotificationDenied |
用户已拒绝显示通知 | 用户主动拒绝,且无法再次弹出授权框(需用户在浏览器设置中手动更改) |
app.NotificationNotSupported |
浏览器不支持通知功能 | window.Notification 不存在,如部分旧浏览器或受限环境 |
从源码实现看(pkg/app/notification.go),NotificationNotSupported 的判定方式是直接检查全局对象是否存在:
// Permission retrieves the current notification permission status.
func (s NotificationService) Permission() NotificationPermission {
notification := Window().Get("Notification")
if !notification.Truthy() {
return NotificationNotSupported
}
return NotificationPermission(notification.Get("permission").String())
}
获取当前权限:Permission()
在组件挂载时通过 ctx.Notifications().Permission() 获取当前权限,这是官方文档给出的标准写法:
type foo struct {
app.Compo
notificationPermission app.NotificationPermission
}
func (f *foo) OnMount(ctx app.Context) {
f.notificationPermission = ctx.Notifications().Permission()
}
将权限状态保存在组件字段中,便于在 Render() 中依据不同状态渲染差异化 UI,也便于后续交互后重新赋值以触发组件更新。
请求权限:RequestPermission()
ctx.Notifications().RequestPermission() 会触发浏览器弹出的授权询问框(popup)。返回值为用户选择后的权限状态。官方文档示例将其绑定在按钮点击事件上:
func (f *foo) Render() app.UI {
return app.Div().Body(
app.If(f.notificationPermission == app.NotificationDefault, func() app.UI {
return app.Button().
Text("Enable Notifications").
OnClick(f.enableNotifications)
}).ElseIf(f.notificationPermission == app.NotificationDenied, func() app.UI {
return app.Text("Notification permission is denied")
}).ElseIf(f.notificationPermission == app.NotificationGranted, func() app.UI {
return app.Text("Notification permission is already granted")
}).Else(func() app.UI {
return app.Text("Notification are not supported")
}),
)
}
func (f *foo) enableNotifications(ctx app.Context, e app.Event) {
// Triggers a browser popup that asks for user permission.
f.notificationPermission = ctx.Notifications().RequestPermission()
}
这里的 app.If / app.ElseIf / app.Else 是 go-app 的条件渲染语法,用于按权限状态渲染不同 UI。从源码看(pkg/app/notification.go),RequestPermission() 内部通过 Promise 异步等待用户选择,随后同步返回结果:
func (s NotificationService) RequestPermission() NotificationPermission {
notification := Window().Get("Notification")
if !notification.Truthy() {
return NotificationNotSupported
}
permission := make(chan string, 1)
defer close(permission)
notification.Call("requestPermission").Then(func(v Value) {
permission <- v.String()
})
return NotificationPermission(<-permission)
}
实战要点:RequestPermission() 只能在用户手势(如点击事件)中调用才会正常弹出授权框;若用户此前选择了"拒绝",浏览器不会再次弹出询问,此时应引导用户在浏览器站点设置中手动开启。
显示本地通知:New() 与 Notification 结构体
获得 app.NotificationGranted 权限后,即可通过 ctx.Notifications().New() 创建并显示本地通知。官方文档示例:
func (f *foo) Render() app.UI {
return app.Div().Body(
app.If(f.notificationPermission == app.NotificationDefault, func() app.UI {
return app.Button().
Text("Enable Notifications").
OnClick(f.enableNotifications)
}).ElseIf(f.notificationPermission == app.NotificationDenied, func() app.UI {
return app.Text("Notification permission is denied")
}).ElseIf(f.notificationPermission == app.NotificationGranted, func() app.UI {
return app.Button().
Text("Test Notification").
OnClick(f.enableNotifications)
}).Else(func() app.UI {
return app.Text("Notification are not supported")
}),
)
}
func (f *foo) testNotification(ctx app.Context, e app.Event) {
ctx.Notifications().New(app.Notification{
Title: "Test",
Body: "A test notification",
Path: "/mypage",
})
}
Notification 结构体全字段说明
app.Notification 结构体在 pkg/app/notification.go 中定义,字段与 JSON 标签一一对应(推送场景下服务端也必须按此 JSON 结构发送)。除文档示例中的 Title、Body、Path 外,还支持以下字段:
| 字段 | JSON 键 | 类型 | 说明 |
|---|---|---|---|
Title |
title |
string |
通知顶部显著显示的标题(必填) |
Path |
path |
string |
点击通知后应用导航到的 URL 路径 |
Body |
body |
string |
标题下方显示的主体内容 |
Lang |
lang |
string |
通知语言,使用 ISO 2 字母语言代码 |
Badge |
badge |
string |
空间受限时用于代表通知的图片 URL |
Tag |
tag |
string |
通知的唯一标识符,用于替换同标签旧通知 |
Icon |
icon |
string |
通知中显示的图标 URL |
Image |
image |
string |
通知中展示的大图 URL |
Data |
data |
map[string]any |
通知关联的任意数据(goapp 键为 go-app 保留) |
Renotify |
renotify |
bool |
新通知替换旧通知时是否再次提醒用户 |
RequireInteraction |
requireInteraction |
bool |
通知保持显示直到用户操作,不自动关闭 |
Silent |
silent |
bool |
通知静默,不发声不振屏 |
Vibrate |
vibrate |
[]int |
设备振动模式(对应 Vibration API) |
Actions |
actions |
[]NotificationAction |
通知内可展示的操作按钮 |
其中 NotificationAction(pkg/app/notification.go)用于定义通知内的可点击操作项:
// NotificationAction represents an actionable item within a notification.
type NotificationAction struct {
// Action is the unique ID associated with the user's action on
// the notification.
Action string `json:"action"`
// Title is the descriptive text shown alongside the action.
Title string `json:"title"`
// Icon is the URL of an image to represent the action.
Icon string `json:"icon,omitempty"`
// Path is the URL to navigate to upon clicking the action.
Path string `json:"path"`
}
Path 导航语义:点击通知跳转应用页面
官方文档特别强调:Notification.Path 是一个指向应用内页面的 URL 路径。当通知被点击时,应用会导航到该 URL 路径。
该语义的底层实现在 docs/app-worker.js 的 notificationclick 事件处理器中(docs/app-worker.js):
self.addEventListener("notificationclick", (event) => {
event.notification.close();
const notification = event.notification;
let path = notification.data.goapp.path;
for (let i in notification.data.goapp.actions) {
const action = notification.data.goapp.actions[i];
if (action.action === event.action) {
path = action.path;
break;
}
}
event.waitUntil(
clients
.matchAll({
type: "window",
})
.then((clientList) => {
for (var i = 0; i < clientList.length; i++) {
let client = clientList[i];
if ("focus" in client) {
client.focus();
client.postMessage({
goapp: {
type: "notification",
path: path,
},
});
return;
}
}
if (clients.openWindow) {
return clients.openWindow(path);
}
})
);
});
可见点击通知后的导航逻辑是:优先聚焦已打开的应用窗口并通过 postMessage 通知其导航;如果没有打开的窗口,则用 clients.openWindow(path) 新开窗口加载对应路径。对于本地通知,前端 JS 的 goappNewNotification 函数同样在点击时调用 goappNav(path) 完成 SPA 内部导航(docs/app.js)。
本地通知的底层实现
New() 的实现将 Notification 结构体序列化为 JSON 后,调用前端注入的 goappNewNotification JS 函数(pkg/app/notification.go):
// New creates and displays a notification to the user.
func (s NotificationService) New(n Notification) {
notification, _ := json.Marshal(n)
Window().Call("goappNewNotification", string(notification))
}
goappNewNotification 在 docs/app.js 中负责实际创建浏览器通知对象:
function goappNewNotification(jsonNotification) {
let notification = JSON.parse(jsonNotification);
const title = notification.title;
delete notification.title;
let path = notification.path;
if (!path) {
path = "/";
}
const webNotification = new Notification(title, notification);
webNotification.onclick = () => {
goappNav(path);
};
}
注意这里的一个细节:当 Path 为空时,点击通知默认导航到根路径 /。
Web 推送通知:完整链路实战
推送通知与本地通知的最大区别在于:消息由远程服务器发送,应用无论运行与否都能接收显示。其链路分为四步:
- 前端通过
Subscribe()获取推送订阅(Push Subscription); - 前端将订阅通过 HTTP 请求注册到推送服务器;
- 推送服务器使用 VAPID 密钥对任意已注册订阅发送推送消息;
- Service Worker 的
push事件接收消息并调用showNotification展示。
第一步:获取通知订阅(Subscribe)
使用 ctx.Notifications().Subscribe("VAPID_PUBLIC_KEY") 获取订阅。官方文档示例:
func (f *foo) enableNotifications(ctx app.Context, e app.Event) {
f.notificationPermission = ctx.Notifications().RequestPermission()
if f.notificationPermission == app.NotificationGranted {
f.registerNotificationSubscription(ctx)
}
}
func (f *foo) registerNotificationSubscription(ctx app.Context) {
sub, err := ctx.Notifications().Subscribe("MY_VAPID_PUBLIC_KEY")
if err != nil {
log.Println("subscribing to push notifications failed:", err)
return
}
}
Subscribe() 的源码实现在 pkg/app/notification.go,其行为要点:
func (s NotificationService) Subscribe(vapIDPublicKey string) (NotificationSubscription, error) {
if vapIDPublicKey == "" {
return NotificationSubscription{}, errors.New("vapid public key is empty")
}
subc := make(chan string, 1)
defer close(subc)
Window().Call("goappSubscribePushNotifications", vapIDPublicKey).Then(func(v Value) {
subc <- v.String()
})
jsSub := <-subc
if jsSub == "" {
return NotificationSubscription{}, errors.
New("push notifications are not supported by the browser")
}
...
}
- 传入的 VAPID 公钥不能为空,否则返回
vapid public key is empty错误; - 若浏览器不支持推送(订阅失败返回空字符串),返回
push notifications are not supported by the browser错误。
前端 JS 函数 goappSubscribePushNotifications 使用 Push API 完成订阅(docs/app.js):
async function goappSubscribePushNotifications(vapIDpublicKey) {
try {
const subscription =
await goappServiceWorkerRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: vapIDpublicKey,
});
return JSON.stringify(subscription);
} catch (err) {
console.error(err);
return "";
}
}
userVisibleOnly: true 表示只接收会向用户显示通知的推送(浏览器强制要求);applicationServerKey 即 VAPID 公钥。
订阅结果对应 app.NotificationSubscription 结构体(pkg/app/notification.go),包含推送服务端点与加密密钥:
// NotificationSubscription encapsulates a PushSubscription from the Push API.
type NotificationSubscription struct {
// Endpoint is the push service endpoint URL.
Endpoint string `json:"endpoint"`
// Keys contains cryptographic keys used for the subscription.
Keys struct {
// Auth is the authentication secret.
Auth string `json:"auth"`
// P256dh is the user's public key, associated with the push
// subscription.
P256dh string `json:"p256dh"`
} `json:"keys"`
}
第二步:将订阅注册到推送服务器
拿到订阅后,需要通过一次普通的 HTTP 请求把它注册到你的推送服务器。官方文档给出的标准做法是在 ctx.Async 中编码 JSON 并 POST:
func (f *foo) registerNotificationSubscription(ctx app.Context) {
sub, err := ctx.Notifications().Subscribe("MY_VAPID_PUBLIC_KEY")
if err != nil {
log.Println("subscribing to push notifications failed:", err)
return
}
ctx.Async(func() {
var body bytes.Buffer
if err := json.NewEncoder(&body).Encode(sub); err != nil {
log.Println("encoding notification subscription failed:", err)
return
}
res, err := http.Post("/PUSH_SERVER_ENDPOINT", "application/json", &body)
if err != nil {
log.Println("registering notification subscription failed:", err)
return
}
defer res.Body.Close()
})
}
ctx.Async 将网络请求放到异步 goroutine 中执行,避免阻塞 UI 线程。注册端点(示例中的 /PUSH_SERVER_ENDPOINT)需要你自行实现——下面介绍服务端如何处理。
第三步:服务端发送推送通知
发送推送通知是在服务端完成的。官方文档基于 webpush-go 包给出一个 http.Handler 实现,支持两个路径:register(接收并保存订阅)与 test(向所有订阅发送测试推送):
func main() {
// ...
http.Handle("/test/notifications/", ¬ificationHandler{
VAPIDPrivateKey: "MY_VAPID_PRIVATE_KEY",
VAPIDPublicKey: "MY_VAPID_PUBLIC_KEY",
})
// ...
}
type notificationHandler struct {
VAPIDPrivateKey string
VAPIDPublicKey string
mutex sync.Mutex
subscriptions map[string]webpush.Subscription
}
func (h *notificationHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch path := path.Base(r.URL.Path); path {
case "register":
h.handleRegistrations(w, r)
case "test":
h.handleTests(w, r)
}
}
接收并存储订阅:register 端点将请求体解码为 webpush.Subscription 并以 Endpoint 为键存入内存 map:
func (h *notificationHandler) handleRegistrations(w http.ResponseWriter, r *http.Request) {
var sub webpush.Subscription
if err := json.NewDecoder(r.Body).Decode(&sub); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
h.mutex.Lock()
defer h.mutex.Unlock()
if h.subscriptions == nil {
h.subscriptions = make(map[string]webpush.Subscription)
}
h.subscriptions[sub.Endpoint] = sub
}
创建并发送通知:test 端点遍历所有订阅,构造 JSON 编码的 app.Notification,通过 webpush.SendNotification 发送:
// handleTests creates and sends a push notification for all the registered
// subscriptions.
func (h *notificationHandler) handleTests(w http.ResponseWriter, r *http.Request) {
h.mutex.Lock()
defer h.mutex.Unlock()
for _, sub := range h.subscriptions {
go func(sub webpush.Subscription) {
body, _ := json.Marshal(app.Notification{
Title: "Push test from server",
Body: "go-app push notification number",
Path: "/mypage"
})
res, err := webpush.SendNotification(body, &sub, &webpush.Options{
VAPIDPrivateKey: h.VAPIDPrivateKey,
VAPIDPublicKey: h.VAPIDPublicKey,
TTL: 30,
})
if err != nil {
app.Log(err)
return
}
defer res.Body.Close()
}(sub)
}
}
关键约定:官方文档明确说明——推送服务器可以用各种编程语言实现,go-app 接收推送通知的唯一要求是:通知消息必须是 JSON 编码的 Notification 结构体(即包含 title、path 等对应 JSON 键)。服务端与前端共享同一个 app.Notification 类型(Go 代码中直接复用该结构体即可),这是推送链路两端数据契约一致性的核心保障。
第四步:Service Worker 接收并展示推送
推送到达浏览器后,由 Service Worker 的 push 事件处理(docs/app-worker.js):
// Push Notifications
self.addEventListener("push", (event) => {
if (!event.data || !event.data.text()) {
return;
}
const notification = JSON.parse(event.data.text());
if (!notification) {
return;
}
const title = notification.title;
delete notification.title;
if (!notification.data) {
notification.data = {};
}
let actions = [];
for (let i in notification.actions) {
const action = notification.actions[i];
actions.push({
action: action.action,
path: action.path,
});
delete action.path;
}
notification.data.goapp = {
path: notification.path,
actions: actions,
};
delete notification.path;
event.waitUntil(self.registration.showNotification(title, notification));
});
这段代码说明了推送链路中的两个关键设计:
- 服务端 JSON 中的
title被单独提取作为通知标题,其余字段作为选项传入showNotification; - 通知的
path与各 action 的path被存入notification.data.goapp(goapp保留键),供notificationclick事件在点击时取出做页面导航——这与前文本地通知的Path导航语义完全一致,保证了本地通知与推送通知的点击行为统一。
官方文档站点的真实运行示例
go-app 官方文档站点(docs/src/notifications-page.go)本身就是一个完整的通知功能演示,页面提供"Enable Notifications"和"Test Notification"两个按钮,并集成本地通知与推送订阅的完整流程,可以作为你实现时的参照模板。
其核心逻辑(docs/src/notifications-page.go):
func (p *notificationsPage) enableNotifications(ctx app.Context, e app.Event) {
p.notificationPermission = ctx.Notifications().RequestPermission()
p.registerSubscription(ctx)
}
func (p *notificationsPage) testNotification(ctx app.Context, e app.Event) {
n := rand.Intn(43)
ctx.Notifications().New(app.Notification{
Title: fmt.Sprintln("go-app test", n),
Body: fmt.Sprintln("Test notification for go-app number", n),
Path: "/notifications#example",
Actions: []app.NotificationAction{
{
Title: "test",
Action: ":test",
Path: "/notifications",
},
},
})
}
func (p *notificationsPage) registerSubscription(ctx app.Context) {
if p.notificationPermission != app.NotificationGranted {
return
}
sub, err := ctx.Notifications().Subscribe(app.Getenv("VAPID_PUBLIC_KEY"))
if err != nil {
app.Log(err)
return
}
ctx.Async(func() {
var body bytes.Buffer
if err := json.NewEncoder(&body).Encode(sub); err != nil {
app.Log(errors.New("encoding notification subscription failed").Wrap(err))
return
}
res, err := http.Post("/test/notifications/register", "application/json", &body)
if err != nil {
app.Log(errors.New("registering notification subscription failed").Wrap(err))
return
}
defer res.Body.Close()
})
}
这个示例体现了几个值得借鉴的实践:
- 权限门控:
registerSubscription仅在NotificationGranted时才执行订阅,避免无谓调用; - 环境变量注入:VAPID 公钥通过
app.Getenv("VAPID_PUBLIC_KEY")从环境读取,不硬编码在源码中; - 按钮状态联动:渲染时根据权限状态禁用/启用按钮(
requestEnabled、testEnabled),引导用户按流程操作; - 通知带操作按钮:
testNotification在通知中附加了一个Actions操作项,点击后导航到通知页面,完整演示了NotificationAction的用法。
实践清单与注意事项
基于以上文档与源码分析,实现通知功能时的完整检查清单:
- 权限流程:
OnMount中调用Permission()获取初始状态 → 依据状态渲染 UI → 用户点击时调用RequestPermission()→ 更新状态并触发重新渲染。 - 权限边界:
RequestPermission必须在用户手势事件中调用;Denied状态下浏览器不会再次弹窗,需引导用户去浏览器设置;NotSupported状态需优雅降级。 - 本地通知:授予权限后调用
New(),务必设置Title(必填)与Path(点击后的导航目标,缺省为/)。 - 推送链路:
Subscribe()需要非空的 VAPID 公钥 → 将返回的NotificationSubscriptionJSON 注册到自己的推送服务器 → 服务端用 VAPID 私钥通过 webpush-go 等库向订阅的Endpoint发送 JSON 编码的Notification。 - 数据契约:服务端发送的消息必须是 JSON 编码的
Notification结构体(title、path、body、actions等键),两端共享同一 Go 类型是避免契约漂移的最佳实践。 - 点击导航:无论本地还是推送通知,点击后的页面跳转都基于
Path语义,由 Service Worker(推送场景)或前端 JS(本地场景)统一处理。
深入阅读
- 通知 API 的完整实现:pkg/app/notification.go(
Notification、NotificationAction、NotificationSubscription、NotificationPermission、NotificationService全部定义于此) - 通知服务的入口方法:pkg/app/context.go
- 官方文档站点演示页:docs/src/notifications-page.go
- 推送接收与点击导航的 Service Worker 实现:docs/app-worker.js
- 订阅与本地通知的前端 JS 实现:docs/app.js