webpush

package module
v2.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 8, 2024 License: MIT Imports: 23 Imported by: 0

README

webpush-go

Go Report Card GoDoc

Web Push API Encryption with VAPID support.

go get -u github.com/hcarriz/webpush-go/v2

This project is a fork of github.com/SherClockHolmes/webpush-go/v2

Example

For a full example, refer to the code in the example directory.

package main

import (
	"encoding/json"

	webpush "github.com/hcarriz/webpush-go/v2"
)

func main() {
	// Decode subscription
	s := &webpush.Subscription{}
	json.Unmarshal([]byte("<YOUR_SUBSCRIPTION>"), s)

	// Send Notification
	resp, err := webpush.SendNotification([]byte("Test"), s, &webpush.Options{
		Subscriber:      "example@example.com",
		VAPIDPublicKey:  "<YOUR_VAPID_PUBLIC_KEY>",
		VAPIDPrivateKey: "<YOUR_VAPID_PRIVATE_KEY>",
		TTL:             30,
	})
	if err != nil {
		// TODO: Handle error
	}
	defer resp.Body.Close()
}
Generating VAPID Keys

Use the helper method GenerateVAPIDKeys to generate the VAPID key pair.

privateKey, publicKey, err := webpush.GenerateVAPIDKeys()
if err != nil {
	// TODO: Handle error
}

Development

  1. Install Go 1.11+
  2. go mod vendor
  3. go test
For other language implementations visit:

WebPush Libs

Documentation

Index

Constants

View Source
const (
	MaxRecordSize   uint32 = 4096
	DefaultDuration        = time.Second * 30
	DefaultTimeout         = time.Second * 30
	DefaultTTL             = time.Second * 30
)

Variables

View Source
var (
	ErrMaxPadExceeded = errors.New("payload has exceeded the maximum length")
	ErrNilClient      = errors.New("client is nil")
	ErrEmptyParameter = errors.New("parameter is empty")
	ErrInvalidUrgency = errors.New("urgency is invalid")

	ErrNilSubscriptionEndpoint   = errors.New("subscription endpoint is nil")
	ErrMissingSubscriptionAuth   = errors.New("subscription is missing auth key")
	ErrMissingSubscriptionP256DH = errors.New("subscription is missing p256dh key")
	ErrInvalidSubscriber         = errors.New("subscriber is neither a valid email or a https link")
)

Functions

func GenerateVAPIDKeys

func GenerateVAPIDKeys() (privateKey, publicKey string, err error)

GenerateVAPIDKeys will create a private and public VAPID key pair

func ValidUrgency

func ValidUrgency(urgency Urgency) bool

Checking allowable values for the urgency header

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client configuration that's needed to send a notification.

func New

func New(sub, private, public string, opts ...Option) (*Client, error)

func (*Client) Send

func (o *Client) Send(subscription Subscription, message []byte) (*http.Response, error)

Send calls SendWithContext with default context for backwards-compatibility

func (*Client) SendWithContext

func (o *Client) SendWithContext(ctx context.Context, s Subscription, message []byte, overrides ...Option) (*http.Response, error)

SendWithContext sends a push notification to a subscription's endpoint Message Encryption for Web Push, and VAPID protocols. FOR MORE INFORMATION SEE RFC8291: https://datatracker.ietf.org/doc/rfc8291

func (*Client) Set

func (o *Client) Set(opts ...Option) error

func (Client) SkipForEndpoint added in v2.0.1

func (c Client) SkipForEndpoint(endpoint string) bool

Check if the client will skip the endpoint.

Example: if you use SetTTL(0, "windows.com"), it will return true for "https://wns2-by3p.notify.windows.com/....".

type HTTPClient

type HTTPClient interface {
	Do(*http.Request) (*http.Response, error)
}

HTTPClient is an interface for sending the notification HTTP request / testing

type Keys

type Keys struct {
	Auth   string `json:"auth"`
	P256dh string `json:"p256dh"`
}

Keys are the base64 encoded values from PushSubscription.getKey()

type MissingParameter

type MissingParameter string

func (MissingParameter) Error

func (mp MissingParameter) Error() string

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option configures the client.

func SetClient

func SetClient(client HTTPClient) Option

Clients sets the client to be used for the request.

client can not be nil

func SetExpirationDuration

func SetExpirationDuration(d time.Duration) Option

Set the expiration for VAPID JWT token

Duration is capped to 24 hours. See https://www.rfc-editor.org/rfc/rfc8292#section-2

func SetPrivateKey

func SetPrivateKey(key string) Option

Set the private key to be used.

Key can not be empty.

func SetPublicKey

func SetPublicKey(key string) Option

Set the public key to be used.

Key can not be empty.

func SetRecordSize

func SetRecordSize(size uint32) Option

SetRecordSize is used to limit the record size.

func SetSubscriber

func SetSubscriber(sub string) Option

Set the subscriber in the JWT token.

sub can not be empty.

func SetTTL

func SetTTL(ttl int, exclude ...string) Option

Set the TTL in seconds on the endpoint POST request.

Certain browsers may have issues when TTL is set to 0. TTL must be >= 0 to be set.

You can set the domains to exclude the zero ttl header with the exclude variable. This is not recommended.

func SetTTLDuration added in v2.1.0

func SetTTLDuration(ttl time.Duration) Option

Set the TTL Duration on the endpoint POST request.

Certain browsers may have issues when the TTL is set to 0.

func SetTopic

func SetTopic(topic string) Option

SetTopic can set the SetTopic header to collapse a pending messages

func SetUrgency

func SetUrgency(urgency Urgency) Option

Set the Urgency header to change a message priority

type Subscription

type Subscription struct {
	Endpoint string `json:"endpoint"`
	Keys     Keys   `json:"keys"`
}

Subscription represents a PushSubscription object from the Push API

func (Subscription) Validate added in v2.0.1

func (s Subscription) Validate() error

Validate will check that everything is correct.

type Urgency

type Urgency string

Urgency indicates to the push service how important a message is to the user. This can be used by the push service to help conserve the battery life of a user's device by only waking up for important messages when battery is low.

const (
	// UrgencyVeryLow requires device state: on power and Wi-Fi
	UrgencyVeryLow Urgency = "very-low"
	// UrgencyLow requires device state: on either power or Wi-Fi
	UrgencyLow Urgency = "low"
	// UrgencyNormal excludes device state: low battery
	UrgencyNormal Urgency = "normal"
	// UrgencyHigh admits device state: low battery
	UrgencyHigh Urgency = "high"
)

func (Urgency) String

func (u Urgency) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL