pushbell

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2025 License: MIT Imports: 8 Imported by: 0

README

pushbell

GitHub Release GitHub License Go Report Card

pushbell is a Go library for sending web push notifications with support for the VAPID (Voluntary Application Server Identification) specification.

Features

  • Full implementation of the encryption and Web Push specification, including VAPID.
  • Support for multiple push services (Firefox, Chrome, etc.).
  • Use fasthttp client.
  • Simple and intuitive API.

Installation

go get -u github.com/gootsolution/pushbell

Example

package main

import (
	"github.com/gootsolution/pushbell"
)

func main() {
	applicationServerPrivateKey := "QxfAyO5dMMrSvDT2_xHxW5aktYPWGE_hT42RKlHilpQ"
	applicationServerPublicKey := "BIRM67G3W1fva-ephDo220BbiaOOy-SBk2uzHsmlqMXp_OmkKxYW96cOK5EWnKdkLg2i7N4FYfuxIwm7JWThVSY"

	opts := pushbell.NewOptions().ApplyKeys(applicationServerPublicKey, applicationServerPrivateKey)

	pb, err := pushbell.NewService(opts)
	if err != nil {
		panic(err)
	}

	subscriptionEndpoint := "https://fcm.googleapis.com/fcm/send/e2CN0r8ft38:APA91bES3NaBHe_GgsRp_3Ir7f18L38wA5XYRoqZCbjMPEWnkKa07uxheWE5MGZncsPOr0_34zLaFljVqmNqW76KhPSrjdy_pdInnHPEIYAZpdcIYk8oIfo1F_84uKMSqIDXRhngL76S"
	subscriptionAuth := "rm_owGF0xliyVXsrZk1LzQ"
	subscriptionP256DH := "BKm5pKbGwkTxu7dJuuLyTCBOCuCi1Fs01ukzjUL5SEX1-b-filqeYASY6gy_QpPHGErGqAyQDYAtprNWYdcsM3Y"

	message := []byte("{\"title\": \"My first message\"}")

	err = pb.Send(&pushbell.Push{
		Endpoint:  subscriptionEndpoint,
		Auth:      subscriptionAuth,
		P256DH:    subscriptionP256DH,
		Plaintext: message,
	})
	if err != nil {
		panic(err)
	}
}

NOTE: You can use this to play around and make tests without your service workers.

Documentation

Detailed API documentation is available on GoDoc.

License

This project is distributed under the MIT License.

Support and Contributing

If you have any questions, issues, or suggestions, please create an issue in this repository. Pull requests with fixes and improvements are also welcome.

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrPushBadRequest is returned when the push subscription request is malformed
	ErrPushBadRequest = errors.New("bad request: check the push subscription data and payload format")
	// ErrPushUnauthorized is returned when push service authentication is required
	ErrPushUnauthorized = errors.New("unauthorized: the push service requires valid authentication")
	// ErrPushForbidden is returned when the push service refuses to fulfill the request
	ErrPushForbidden = errors.New("forbidden: the push service understood the request, but is refusing to fulfill it")
	// ErrPushNotFound is returned when the push subscription cannot be found
	ErrPushNotFound = errors.New("push subscription not found: the user may have unsubscribed or the subscription may have expired")
	// ErrPushGone is returned when the push subscription is no longer active
	ErrPushGone = errors.New("push subscription is no longer active: delete it from your database")
	// ErrPushTooManyRequests is returned when the push service rate limit is exceeded or when GSB ban occurs
	ErrPushTooManyRequests = errors.New("too many push requests or GSB ban: try again later")
	// ErrPushInternalServerError is returned for push service server errors
	ErrPushInternalServerError = errors.New("push service internal server error: try again later")
	// ErrPushServiceUnavailable is returned when the push service is temporarily unavailable
	ErrPushServiceUnavailable = errors.New("push service unavailable: try again later")
	// ErrPushUnexpectedResponse is returned for unexpected status codes from push service
	ErrPushUnexpectedResponse = errors.New("unexpected response from the push service")
)

Functions

func ValidateStatusCode added in v1.1.0

func ValidateStatusCode(statusCode int) error

ValidateStatusCode takes an HTTP status code and returns an error if the status code indicates an error condition. It can be used to easily handle different types of errors that can occur when making HTTP requests.

Types

type Options added in v1.0.0

type Options struct {
	ApplicationServerPublicKey  string                   // [RFC 8292] ECDH public key.
	ApplicationServerPrivateKey string                   // [RFC 8292] ECDH private key.
	ApplicationServerSubject    string                   // [RFC 8292] Either a "mailto:" (email) or a "https:" URI.
	StatusCodeValidationFunc    StatusCodeValidationFunc // [Optional] If set, use function that validates status codes and returns errors accordingly.
	HttpClient                  httpclient.Client        // [Optional] Custom client for request.
	KeyRotationInterval         time.Duration            // [Optional] If set, enable encryption keys rotation.
}

Options configures the push notification service settings.

func NewOptions added in v1.0.0

func NewOptions() *Options

NewOptions creates and returns a new Options instance with default settings. By default, it sets the ApplicationServerSubject to the project's GitHub URL.

func (*Options) ApplyKeys added in v1.0.0

func (o *Options) ApplyKeys(publicKey, privateKey string) *Options

ApplyKeys sets the ECDH public and private keys used for web push encryption. These keys are required for secure communication according to RFC 8292. Returns the updated Options instance for method chaining.

func (*Options) SetFastHttpClient added in v1.0.0

func (o *Options) SetFastHttpClient(client *fasthttp.Client) *Options

SetFastHttpClient sets a fasthttp client for making web push requests. fasthttp can provide better performance in certain scenarios. Returns the updated Options instance for method chaining.

func (*Options) SetHttpClient added in v1.1.0

func (o *Options) SetHttpClient(client httpclient.Client) *Options

SetHttpClient sets a custom HTTP client for making web push requests. This allows for greater control over HTTP connection parameters. Returns the updated Options instance for method chaining.

func (*Options) SetKeyRotationEnabled added in v1.1.0

func (o *Options) SetKeyRotationEnabled() *Options

SetKeyRotationEnabled enables encryption key rotation for improved security. Key rotation helps reduce the risk associated with compromised encryption keys. Returns the updated Options instance for method chaining.

func (*Options) SetKeyRotationInterval added in v1.1.0

func (o *Options) SetKeyRotationInterval(interval time.Duration) *Options

SetKeyRotationInterval enables key rotation and sets the interval duration between key rotations. This provides more control over the key rotation schedule. Returns the updated Options instance for method chaining.

func (*Options) SetStatusCodeValidationFunc added in v1.1.0

func (o *Options) SetStatusCodeValidationFunc(validationFunc StatusCodeValidationFunc) *Options

SetStatusCodeValidationFunc sets a custom function for HTTP status code validation. This function will be used to determine if a response should be treated as an error based on its status code. Returns the updated Options instance for method chaining.

func (*Options) SetStdHttpClient added in v1.0.0

func (o *Options) SetStdHttpClient(client *http.Client) *Options

SetStdHttpClient sets a standard library http client for making web push requests. This is useful when the standard http package is preferred. Returns the updated Options instance for method chaining.

func (*Options) SetSubject added in v1.0.0

func (o *Options) SetSubject(subject string) *Options

SetSubject sets the application server subject. According to RFC 8292, this should be either a "mailto:" email address or an "https:" URI to identify the application server. Returns the updated Options instance for method chaining.

type Push added in v1.0.0

type Push struct {
	Endpoint  string
	Auth      string
	P256DH    string
	Plaintext []byte
	Urgency   Urgency
	TTL       time.Duration
}

type Service

type Service struct {
	Encryption               *encryption.Service
	Vapid                    *vapid.Service
	Client                   httpclient.Client
	StatusCodeValidationFunc StatusCodeValidationFunc
}

Service contains all dependencies needed for sending web push notifications.

func NewService added in v1.0.0

func NewService(options *Options) (*Service, error)

NewService creates new service with given application server keys and subject.

Example
applicationServerPublicKey := "BIRM67G3W1fva-ephDo220BbiaOOy-SBk2uzHsmlqMXp_OmkKxYW96cOK5EWnKdkLg2i7N4FYfuxIwm7JWThVSY"
applicationServerPrivateKey := "QxfAyO5dMMrSvDT2_xHxW5aktYPWGE_hT42RKlHilpQ"

opts := NewOptions().ApplyKeys(applicationServerPublicKey, applicationServerPrivateKey)

pb, err := NewService(opts)
if err != nil {
	panic(err)
}

subscriptionEndpoint := "https://fcm.googleapis.com/fcm/send/e2CN0r8ft38:APA91bES3NaBHe_GgsRp_3Ir7f18L38wA5XYRoqZCbjMPEWnkKa07uxheWE5MGZncsPOr0_34zLaFljVqmNqW76KhPSrjdy_pdInnHPEIYAZpdcIYk8oIfo1F_84uKMSqIDXRhngL76S"
subscriptionAuth := "rm_owGF0xliyVXsrZk1LzQ"
subscriptionP256DH := "BKm5pKbGwkTxu7dJuuLyTCBOCuCi1Fs01ukzjUL5SEX1-b-filqeYASY6gy_QpPHGErGqAyQDYAtprNWYdcsM3Y"
message := []byte("{\"title\": \"My first message\"}")

err = pb.Send(&Push{
	Endpoint:  subscriptionEndpoint,
	Auth:      subscriptionAuth,
	P256DH:    subscriptionP256DH,
	Plaintext: message,
})
if err != nil {
	switch {
	case errors.Is(err, ErrPushGone):
		log.Println("user unsubscribed")
	default:
		log.Println(err)
	}
}

func (*Service) Send

func (s *Service) Send(push *Push) error

Send sends a WebPush notification with parameters to the specified endpoint.

type StatusCodeValidationFunc added in v1.1.0

type StatusCodeValidationFunc func(statusCode int) error

StatusCodeValidationFunc is a function type that validates HTTP status codes

type Urgency

type Urgency string
const (
	UrgencyVeryLow Urgency = "very-low" // Device State - On power and Wi-Fi
	UrgencyLow     Urgency = "low"      // Device State - On either power or Wi-Fi
	UrgencyNormal  Urgency = "normal"   // Device State - On neither power nor Wi-Fi
	UrgencyHigh    Urgency = "high"     // Device State - Low battery
)

Directories

Path Synopsis
pkg

Jump to

Keyboard shortcuts

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