sdk

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Apr 14, 2026 License: MIT Imports: 19 Imported by: 0

README

pgns Go SDK

Go client library for the pgns webhook relay API.

Installation

go get github.com/pgns-io/sdk-go

Quick Start

package main

import (
	"context"
	"fmt"

	pgns "github.com/pgns-io/sdk-go"
)

func main() {
	client := pgns.NewClient("your-api-key")

	// List roosts
	roosts, err := client.Roosts.List(context.Background())
	if err != nil {
		panic(err)
	}
	fmt.Println(roosts)

	// Send a pigeon
	err = client.Pigeons.Send(context.Background(), "rst_abc123", map[string]any{
		"event": "user.created",
		"data":  map[string]any{"id": 1},
	})
	if err != nil {
		panic(err)
	}
}

Documentation

Full documentation is available at docs.pgns.io/sdks/go.

API reference: pkg.go.dev/github.com/pgns-io/sdk-go

License

MIT

Documentation

Overview

Package sdk provides a Go client for the pgns webhook relay API.

The client supports two authentication modes:

  • API key — pass WithAPIKey for server-side usage.
  • JWT — pass WithAccessToken. Expired tokens are refreshed automatically on 401.

Quick start

client := sdk.NewClient("https://api.pgns.io", sdk.WithAPIKey("pk_live_..."))
roosts, err := client.ListRoosts(ctx)

Index

Constants

View Source
const Version = "0.4.0"

Version is the current version of the pgns Go SDK.

Variables

This section is empty.

Functions

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err is a PigeonsError with status 404.

func IsUnauthorized

func IsUnauthorized(err error) bool

IsUnauthorized reports whether err is a PigeonsError with status 401.

Types

type ApiKeyCreatedResponse

type ApiKeyCreatedResponse struct {
	ID        string `json:"id"`
	Key       string `json:"key"`
	KeyPrefix string `json:"key_prefix"`
	Name      string `json:"name"`
	CreatedAt string `json:"created_at"`
}

ApiKeyCreatedResponse includes the full key (shown only once).

type ApiKeyResponse

type ApiKeyResponse struct {
	ID        string  `json:"id"`
	KeyPrefix string  `json:"key_prefix"`
	Name      string  `json:"name"`
	LastUsed  *string `json:"last_used"`
	RevokedAt *string `json:"revoked_at"`
	CreatedAt string  `json:"created_at"`
}

ApiKeyResponse is an API key without the full key value.

type AuthTokens

type AuthTokens struct {
	AccessToken string `json:"access_token"`
	TokenType   string `json:"token_type"`
	ExpiresIn   int    `json:"expires_in"`
}

AuthTokens is returned by authentication endpoints.

type Client

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

Client is a Go client for the pgns webhook relay API.

func NewClient

func NewClient(baseURL string, opts ...Option) *Client

NewClient creates a new pgns API client.

func (*Client) CreateApiKey

func (c *Client) CreateApiKey(ctx context.Context, req *CreateApiKeyRequest) (ApiKeyCreatedResponse, error)

CreateApiKey creates a new API key. The full key is only in this response.

func (*Client) CreateDestination

func (c *Client) CreateDestination(ctx context.Context, roostID string, req CreateDestination) (Destination, error)

CreateDestination adds a new destination to a roost.

func (*Client) CreateRoost

func (c *Client) CreateRoost(ctx context.Context, req CreateRoost) (Roost, error)

CreateRoost creates a new roost (webhook endpoint).

func (*Client) CreateTemplate

func (c *Client) CreateTemplate(ctx context.Context, req CreateTemplate) (Template, error)

CreateTemplate creates a new template.

func (*Client) DeleteApiKey

func (c *Client) DeleteApiKey(ctx context.Context, keyID string) error

DeleteApiKey permanently revokes and deletes an API key.

func (*Client) DeleteDestination

func (c *Client) DeleteDestination(ctx context.Context, destinationID string) error

DeleteDestination permanently deletes a destination.

func (*Client) DeleteRoost

func (c *Client) DeleteRoost(ctx context.Context, roostID string) error

DeleteRoost deletes a roost and all its destinations.

func (*Client) DeleteTemplate

func (c *Client) DeleteTemplate(ctx context.Context, templateID string) error

DeleteTemplate deletes a template.

func (*Client) GetApiKey

func (c *Client) GetApiKey(ctx context.Context, keyID string) (ApiKeyResponse, error)

GetApiKey returns an API key by ID (does not return the full key value).

func (*Client) GetDestination

func (c *Client) GetDestination(ctx context.Context, destinationID string) (Destination, error)

GetDestination returns a destination by ID.

func (*Client) GetMe

func (c *Client) GetMe(ctx context.Context) (User, error)

GetMe returns the authenticated user's profile.

func (*Client) GetPigeon

func (c *Client) GetPigeon(ctx context.Context, pigeonID string) (Pigeon, error)

GetPigeon returns a single pigeon by ID.

func (*Client) GetPigeonDeliveries

func (c *Client) GetPigeonDeliveries(ctx context.Context, pigeonID string, opts *ListDeliveriesOptions) (PaginatedDeliveryAttempts, error)

GetPigeonDeliveries returns delivery attempts for a pigeon.

func (*Client) GetRoost

func (c *Client) GetRoost(ctx context.Context, roostID string) (Roost, error)

GetRoost returns a roost by ID.

func (*Client) GetTemplate

func (c *Client) GetTemplate(ctx context.Context, templateID string) (Template, error)

GetTemplate returns a template by ID.

func (*Client) ListApiKeys

func (c *Client) ListApiKeys(ctx context.Context) ([]ApiKeyResponse, error)

ListApiKeys returns all API keys for the authenticated user.

func (*Client) ListDestinations

func (c *Client) ListDestinations(ctx context.Context, roostID string) ([]Destination, error)

ListDestinations returns all destinations for a roost.

func (*Client) ListPigeons

func (c *Client) ListPigeons(ctx context.Context, opts *ListPigeonsOptions) (PaginatedPigeons, error)

ListPigeons returns a paginated list of pigeons.

func (*Client) ListRoosts

func (c *Client) ListRoosts(ctx context.Context) ([]Roost, error)

ListRoosts returns all roosts for the authenticated user.

func (*Client) ListTemplates

func (c *Client) ListTemplates(ctx context.Context) ([]Template, error)

ListTemplates returns all templates for the authenticated user.

func (*Client) ListenEvents

func (c *Client) ListenEvents(ctx context.Context, onEvent func(data string), opts ...EventOption) error

ListenEvents connects to the SSE event stream and calls onEvent for each event received. It automatically reconnects on failure with a 3-second delay. On reconnect, the Last-Event-ID header is sent so the server can replay missed events. The function blocks until ctx is cancelled.

func (*Client) Logout

func (c *Client) Logout(ctx context.Context) error

Logout revokes the refresh token and clears stored credentials.

func (*Client) PauseDestination

func (c *Client) PauseDestination(ctx context.Context, destinationID string, isPaused bool) (PauseResponse, error)

PauseDestination pauses or unpauses delivery to a destination.

func (*Client) PreviewTemplate

PreviewTemplate renders a template with a pigeon's data.

func (*Client) Refresh

func (c *Client) Refresh(ctx context.Context) (AuthTokens, error)

Refresh refreshes the access token using the httpOnly refresh cookie.

func (*Client) ReplayPigeon

func (c *Client) ReplayPigeon(ctx context.Context, pigeonID string) (ReplayResponse, error)

ReplayPigeon re-delivers a pigeon to all active destinations.

func (*Client) Send added in v0.3.0

func (c *Client) Send(ctx context.Context, opts SendOptions) (SendResponse, error)

Send sends a signed webhook to a roost.

It computes dual signatures: legacy X-Pigeon-Signature (hex) and Standard Webhooks webhook-signature (base64). Both header sets are sent for backward compatibility.

func (*Client) SetAPIKey

func (c *Client) SetAPIKey(key string)

SetAPIKey replaces the current API key.

func (*Client) SetAccessToken

func (c *Client) SetAccessToken(token string)

SetAccessToken replaces the current JWT access token.

func (*Client) UpdateApiKey

func (c *Client) UpdateApiKey(ctx context.Context, keyID string, req UpdateApiKeyRequest) (ApiKeyResponse, error)

UpdateApiKey renames an API key.

func (*Client) UpdateDestination added in v0.3.0

func (c *Client) UpdateDestination(ctx context.Context, destinationID string, req UpdateDestination) (Destination, error)

UpdateDestination updates a destination's name or configuration.

func (*Client) UpdateMe

func (c *Client) UpdateMe(ctx context.Context, req UpdateProfileRequest) (User, error)

UpdateMe updates the authenticated user's profile.

func (*Client) UpdateRoost

func (c *Client) UpdateRoost(ctx context.Context, roostID string, req UpdateRoost) (Roost, error)

UpdateRoost updates a roost's name, description, secret, or active state.

func (*Client) UpdateTemplate

func (c *Client) UpdateTemplate(ctx context.Context, templateID string, req UpdateTemplate) (Template, error)

UpdateTemplate updates a template.

type CreateApiKeyRequest

type CreateApiKeyRequest struct {
	Name *string `json:"name,omitempty"`
}

CreateApiKeyRequest is the body for POST /v1/api-keys.

type CreateDestination

type CreateDestination struct {
	DestinationType  string         `json:"destination_type"`
	Name             *string        `json:"name,omitempty"`
	Config           map[string]any `json:"config,omitempty"`
	FilterExpression *string        `json:"filter_expression,omitempty"`
	Template         *string        `json:"template,omitempty"`
	RetryMax         *int           `json:"retry_max,omitempty"`
	RetryDelayMs     *int           `json:"retry_delay_ms,omitempty"`
	RetryMultiplier  *float64       `json:"retry_multiplier,omitempty"`
}

CreateDestination is the body for POST /v1/roosts/:id/destinations.

type CreateRoost

type CreateRoost struct {
	Name        string  `json:"name"`
	Description *string `json:"description,omitempty"`
	Secret      *string `json:"secret,omitempty"`
	SourceType  *string `json:"source_type,omitempty"`
	Schema      any     `json:"schema,omitempty"`
}

CreateRoost is the body for POST /v1/roosts.

type CreateTemplate

type CreateTemplate struct {
	Name        string  `json:"name"`
	Description *string `json:"description,omitempty"`
	Body        *string `json:"body,omitempty"`
}

CreateTemplate is the body for POST /v1/templates.

type DeliveryAttempt

type DeliveryAttempt struct {
	ID              string            `json:"id"`
	PigeonID        string            `json:"pigeon_id"`
	DestinationID   string            `json:"destination_id"`
	Status          string            `json:"status"`
	AttemptNumber   int               `json:"attempt_number"`
	ResponseStatus  *int              `json:"response_status"`
	ResponseBody    *string           `json:"response_body"`
	ResponseHeaders map[string]string `json:"response_headers,omitempty"`
	RequestHeaders  map[string]string `json:"request_headers,omitempty"`
	RequestBody     *string           `json:"request_body,omitempty"`
	ErrorMessage    *string           `json:"error_message"`
	AttemptedAt     string            `json:"attempted_at"`
	NextRetryAt     *string           `json:"next_retry_at"`
}

DeliveryAttempt is a single attempt to deliver a pigeon to a destination.

type Destination

type Destination struct {
	ID               string         `json:"id"`
	RoostID          string         `json:"roost_id"`
	Name             string         `json:"name"`
	DestinationType  string         `json:"destination_type"`
	Config           map[string]any `json:"config"`
	FilterExpression string         `json:"filter_expression"`
	Template         string         `json:"template"`
	RetryMax         int            `json:"retry_max"`
	RetryDelayMs     int            `json:"retry_delay_ms"`
	RetryMultiplier  float64        `json:"retry_multiplier"`
	IsPaused         bool           `json:"is_paused"`
	IsVerified       bool           `json:"is_verified"`
	CreatedAt        string         `json:"created_at"`
	UpdatedAt        string         `json:"updated_at"`
}

Destination is a forwarding target attached to a roost.

type EventOption

type EventOption func(*eventConfig)

EventOption configures Client.ListenEvents.

func WithErrorHandler

func WithErrorHandler(fn func(error)) EventOption

WithErrorHandler registers a callback for connection errors.

func WithRoostID

func WithRoostID(id string) EventOption

WithRoostID restricts the event stream to a single roost.

type ListDeliveriesOptions

type ListDeliveriesOptions struct {
	Limit  int
	Cursor string
}

ListDeliveriesOptions configures the GetPigeonDeliveries call.

type ListPigeonsOptions

type ListPigeonsOptions struct {
	RoostID string
	Limit   int
	Cursor  string
}

ListPigeonsOptions configures the ListPigeons call.

type Option

type Option func(*Client)

Option configures a Client.

func WithAPIKey

func WithAPIKey(key string) Option

WithAPIKey sets the API key for authentication.

func WithAccessToken

func WithAccessToken(token string) Option

WithAccessToken sets the JWT access token for authentication.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient sets a custom HTTP client.

func WithTokenRefreshHandler

func WithTokenRefreshHandler(fn func(AuthTokens)) Option

WithTokenRefreshHandler registers a callback invoked after a token refresh.

type PaginatedDeliveryAttempts

type PaginatedDeliveryAttempts struct {
	Data       []DeliveryAttempt `json:"data"`
	NextCursor *string           `json:"next_cursor"`
	HasMore    bool              `json:"has_more"`
}

PaginatedDeliveryAttempts is a paginated list of delivery attempts.

type PaginatedPigeons

type PaginatedPigeons struct {
	Data       []Pigeon `json:"data"`
	NextCursor *string  `json:"next_cursor"`
	HasMore    bool     `json:"has_more"`
}

PaginatedPigeons is a paginated list of pigeons.

type PauseInput

type PauseInput struct {
	IsPaused bool `json:"is_paused"`
}

PauseInput is the body for PATCH /v1/destinations/:id/pause.

type PauseResponse

type PauseResponse struct {
	IsPaused bool `json:"is_paused"`
}

PauseResponse is returned by PATCH /v1/destinations/:id/pause.

type Pigeon

type Pigeon struct {
	ID             string         `json:"id"`
	RoostID        string         `json:"roost_id"`
	SourceIP       string         `json:"source_ip"`
	RequestMethod  string         `json:"request_method"`
	ContentType    string         `json:"content_type"`
	Headers        map[string]any `json:"headers"`
	BodyJSON       any            `json:"body_json"`
	BodyRaw        []int          `json:"body_raw"`
	RequestQuery   map[string]any `json:"request_query"`
	ReplayedFrom   *string        `json:"replayed_from"`
	DeliveryStatus string         `json:"delivery_status"`
	ReceivedAt     string         `json:"received_at"`
	CorrelationID  *string        `json:"correlation_id"`
}

Pigeon is a captured webhook request.

type PigeonsError

type PigeonsError struct {
	Message    string
	StatusCode int
	Code       string
}

PigeonsError is returned when the pgns API responds with a non-2xx status.

func (*PigeonsError) Error

func (e *PigeonsError) Error() string

type PreviewTemplateRequest

type PreviewTemplateRequest struct {
	Body     string `json:"body"`
	PigeonID string `json:"pigeon_id"`
}

PreviewTemplateRequest is the body for POST /v1/templates/preview.

type PreviewTemplateResponse

type PreviewTemplateResponse struct {
	Rendered string `json:"rendered"`
}

PreviewTemplateResponse is returned by POST /v1/templates/preview.

type ReplayResponse

type ReplayResponse struct {
	Replayed         bool   `json:"replayed"`
	PigeonID         string `json:"pigeon_id"`
	DeliveryAttempts int    `json:"delivery_attempts"`
}

ReplayResponse is returned by POST /v1/pigeons/:id/replay.

type Roost

type Roost struct {
	ID          string  `json:"id"`
	Name        string  `json:"name"`
	Description string  `json:"description"`
	Secret      *string `json:"secret"`
	SourceType  *string `json:"source_type"`
	Schema      any     `json:"schema"`
	IsActive    bool    `json:"is_active"`
	CreatedAt   string  `json:"created_at"`
	UpdatedAt   string  `json:"updated_at"`
}

Roost is a webhook endpoint that captures incoming requests.

type SendOptions added in v0.3.0

type SendOptions struct {
	// RoostID is the target roost.
	RoostID string
	// EventType is set as the X-Pigeon-Event-Type header.
	EventType string
	// Payload is the JSON body to send.
	Payload any
	// SigningSecret is the HMAC signing secret for computing signatures.
	SigningSecret string
}

SendOptions configures a Send call.

type SendResponse added in v0.3.0

type SendResponse struct {
	ID           string `json:"id"`
	Status       string `json:"status"`
	Destinations int    `json:"destinations"`
}

SendResponse is returned by Send.

type Template

type Template struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Body        string `json:"body"`
	CreatedAt   string `json:"created_at"`
	UpdatedAt   string `json:"updated_at"`
}

Template is a reusable template for formatting webhook payloads.

type UpdateApiKeyRequest

type UpdateApiKeyRequest struct {
	Name string `json:"name"`
}

UpdateApiKeyRequest is the body for PATCH /v1/api-keys/:id.

type UpdateDestination added in v0.3.0

type UpdateDestination struct {
	Name             *string        `json:"name,omitempty"`
	Config           map[string]any `json:"config,omitempty"`
	FilterExpression *string        `json:"filter_expression,omitempty"`
	Template         *string        `json:"template,omitempty"`
	TransformType    *string        `json:"transform_type,omitempty"`
	TransformCode    *string        `json:"transform_code,omitempty"`
}

UpdateDestination is the body for PATCH /v1/destinations/:id.

type UpdateProfileRequest

type UpdateProfileRequest struct {
	Name  *string `json:"name,omitempty"`
	Email *string `json:"email,omitempty"`
}

UpdateProfileRequest is the body for PATCH /v1/me.

type UpdateRoost

type UpdateRoost struct {
	Name        *string `json:"name,omitempty"`
	Description *string `json:"description,omitempty"`
	Secret      *string `json:"secret,omitempty"`
	SourceType  *string `json:"source_type,omitempty"`
	Schema      any     `json:"schema,omitempty"`
	IsActive    *bool   `json:"is_active,omitempty"`
}

UpdateRoost is the body for PATCH /v1/roosts/:id.

type UpdateTemplate

type UpdateTemplate struct {
	Name        *string `json:"name,omitempty"`
	Description *string `json:"description,omitempty"`
	Body        *string `json:"body,omitempty"`
}

UpdateTemplate is the body for PATCH /v1/templates/:id.

type User

type User struct {
	ID            string  `json:"id"`
	Email         string  `json:"email"`
	Name          string  `json:"name"`
	Plan          string  `json:"plan"`
	DataRegion    string  `json:"data_region"`
	Country       *string `json:"country"`
	TosAcceptedAt *string `json:"tos_accepted_at"`
	MfaEnabled    bool    `json:"mfa_enabled"`
	CreatedAt     string  `json:"created_at"`
	UpdatedAt     string  `json:"updated_at"`
}

User represents an authenticated user account.

Jump to

Keyboard shortcuts

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