Web Push Notifications (Go)
БесплатноБез исполняемых скриптовНе проверенSend Web Push notifications from a Go backend using webpush-go (VAPID authentication, payload encryption, subscription storage, and browser subscribe flow)…
от monaxamo285 установок в других каталогахОб этом скилле
Web Push Notifications (Go)
Отправка push-уведомлений в браузеры (Chrome, Firefox, Edge, Safari) из
Go-бэкенда через библиотеку github.com/SherClockHolmes/webpush-go:
аутентификация VAPID, шифрование payload по Message Encryption for Web Push,
хранение подписок и подписка на стороне браузера.
Это Go-версия навыка web-push (Node.js). Выбирай её, когда бэкенд на Go.
When to Apply
- Отправка push из Go-сервиса (Push API, VAPID, web-push-go).
- Миграция с Node.js-реализации
web-pushна Go. - Хранение подписок в Postgres и рассылка по расписанию.
- Подписка в браузере через Service Worker.
Quick Start
import (
"encoding/json"
"log"
"net/http"
"github.com/SherClockHolmes/webpush-go"
)
func send(sub webpush.Subscription, payload []byte) error {
vapidPublic := "BNc..." // из конфигурации, генерируются ОДИН раз
vapidPrivate := "q1tX..."
subject := "mailto:[email protected]"
_, err := webpush.SendNotification(sub, payload, &webpush.Options{
VAPIDPublicKey: vapidPublic,
VAPIDPrivateKey: vapidPrivate,
Subscriber: subject,
TTL: 3600,
Urgency: webpush.UrgencyNormal,
})
return err
}
webpush.SendNotification сам шифрует payload, формирует заголовки
Authorization (VAPID) и Crypto-Key, ставит Content-Encoding: aes128gcm и сам отправляет POST на endpoint подписки.
Core Workflows
1. Сгенерировать VAPID-ключи (один раз, навсегда)
privateKey, publicKey, err := webpush.GenerateVAPIDKeys()
if err != nil {
log.Fatal(err)
}
fmt.Println("public:", publicKey) // отдаём в браузер
fmt.Println("private:", privateKey) // храним в секретах сервера
Критично: ключи генерируются ОДИН раз и хранятся постоянно. Перегенерация ломает все существующие подписки — браузеры продолжают присылать старую public key, а сервер подписывает новой, и push не доходит.
2. Подписаться в браузере
// service-worker.js
const publicKey = '<VAPID public key (URL-safe base64)>';
self.addEventListener('push', (event) => {
const data = event.data ? event.data.json() : {};
event.waitUntil(
self.registration.showNotification(data.title || 'Уведомление', {
body: data.body || '',
icon: '/icons/icon-192.png',
badge: '/icons/badge-96.png',
tag: data.tag || undefined,
data: { url: data.url || '/' },
})
);
});
self.addEventListener('notificationclick', (event) => {
event.notification.close();
event.waitUntil(clients.openWindow(event.notification.data?.url || '/'));
});
// страница подписки
function urlBase64ToUint8Array(base64String) {
const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
const rawData = window.atob(base64);
return Uint8Array.from([...rawData].map((c) => c.charCodeAt(0)));
}
async function subscribe() {
const reg = await navigator.serviceWorker.register('/service-worker.js');
const sub = await reg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(VAPID_PUBLIC_KEY),
});
await fetch('/api/push/subscribe', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(sub),
});
}
Публичный VAPID-ключ отдаётся клиенту как константа или через
/api/push/key — он не секрет.
3. Принять и сохранить подписку
type Subscription struct {
ID string `json:"id"`
Endpoint string `json:"endpoint"`
P256DH string `json:"p256dh"`
Auth string `json:"auth"`
CreatedAt time.Time `json:"created_at"`
UserID string `json:"user_id"`
}
// POST /api/push/subscribe
func handleSubscribe(w http.ResponseWriter, r *http.Request) {
var in struct {
Endpoint string `json:"endpoint"`
Keys struct {
P256DH string `json:"p256dh"`
Auth string `json:"auth"`
} `json:"keys"`
}
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
http.Error(w, "bad json", http.StatusBadRequest)
return
}
if in.Endpoint == "" || in.Keys.P256DH == "" || in.Keys.Auth == "" {
http.Error(w, "incomplete subscription", http.StatusBadRequest)
return
}
// webpush-go ждёт JSON-подобную структуру: {"endpoint":..,"keys":{..}}
raw, _ := json.Marshal(map[string]any{
"endpoint": in.Endpoint,
"keys": map[string]string{"p256dh": in.Keys.P256DH, "auth": in.Keys.Auth},
})
var sub webpush.Subscription
if err := json.Unmarshal(raw, &sub); err != nil {
http.Error(w, "bad subscription", http.StatusBadRequest)
return
}
// ... сохранить в Postgres: endpoint уникален, апсерт по endpoint
Установить Web Push Notifications (Go) в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл Web Push Notifications (Go)?
Send Web Push notifications from a Go backend using webpush-go (VAPID authentication, payload encryption, subscription storage, and browser subscribe flow). Use when working with Push API subscriptions in Go, Web Push Protocol, VAPID key management, browser push notifications, or migrating a Node web-push implementation to Go. Covers VAPID key generation, encrypting payloads, the aes128gcm encoding, subscription persistence in Postgres, and the browser-side subscribe code.
Как установить скилл Web Push Notifications (Go)?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл Web Push Notifications (Go) запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic