api

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: Apache-2.0 Imports: 21 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package api is the SePay API v2 HTTP client.

Index

Constants

View Source
const APIVersion = "2025-07-01"

APIVersion is the API version pinned on every request.

View Source
const MaxResponseBytes = 10 << 20

MaxResponseBytes caps a response body so a hostile host can't OOM the client.

Variables

View Source
var ErrDotSegment = errors.New(`refusing to send a request whose path has a "." or ".." segment`)

ErrDotSegment refuses a path with a "." or ".." segment, which the server would resolve elsewhere.

View Source
var ErrResponseTooLarge = fmt.Errorf("server response exceeded %d bytes", MaxResponseBytes)

ErrResponseTooLarge is a body over MaxResponseBytes: the server answered, so a resend would only fetch it again.

Functions

func Backoff

func Backoff(retryAfter string, attempt int) time.Duration

Backoff returns the 429 wait: Retry-After seconds, else 1,2,4,... by attempt, capped at maxBackoff. Capped in seconds before converting, since a large value overflows int64 nanoseconds.

func DataInto

func DataInto[T any](env *Envelope) (T, error)

DataInto decodes a single-resource envelope's data into T.

func DebugTransport

func DebugTransport(base http.RoundTripper) http.RoundTripper

DebugTransport logs each request at debug level. Only header names are logged and query values are masked unless listed in unmaskedParams.

func HasDotSegment

func HasDotSegment(rawPath string) bool

HasDotSegment reports a "." or ".." segment in rawPath, decoded or not; query and fragment are ignored.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err is an API 404.

func NewIdempotencyKey

func NewIdempotencyKey() (string, error)

NewIdempotencyKey returns a random key for a mutating request. Generate it once per logical operation and reuse it across retries via WriteOptions so a replay does not create a duplicate.

func NoRedirect

func NoRedirect(*http.Request, []*http.Request) error

NoRedirect refuses redirects so the Bearer token is never resent to another host.

func ReadBody

func ReadBody(resp *http.Response) ([]byte, error)

ReadBody reads and closes a capped response body; a truncated read is an error, not an empty success.

func UserAgent

func UserAgent() string

UserAgent identifies the CLI build.

func WithRequestID

func WithRequestID(err error, h http.Header) error

WithRequestID fills an *HTTPError's missing RequestID from X-Request-Id.

Types

type Client

type Client struct {
	MaxRetries int

	// Reauth returns a replacement token after a 401 ("" for none). Any verb is replayed:
	// the 401 comes from the auth filter before a handler runs.
	Reauth func(ctx context.Context, rejected string) string

	// Logf, if set, reports progress such as a 429 retry.
	Logf func(format string, args ...any)
	// contains filtered or unexported fields
}

Client calls the SePay API v2 over HTTP.

func NewClient

func NewClient(baseURL, token string) *Client

NewClient returns a Client for baseURL authenticated with token.

func (*Client) BaseURL

func (c *Client) BaseURL() string

BaseURL returns the resolved API base, including its version segment.

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, path string, opts WriteOptions) (*Envelope, error)

Delete sends DELETE path and returns the envelope (empty on 204).

func (*Client) Get

func (c *Client) Get(ctx context.Context, path string, query url.Values) (*Envelope, error)

Get sends GET path and returns the unwrapped envelope.

func (*Client) Post

func (c *Client) Post(ctx context.Context, path string, opts WriteOptions) (*Envelope, error)

Post sends POST path with an optional JSON body and returns the envelope.

func (*Client) Put

func (c *Client) Put(ctx context.Context, path string, opts WriteOptions) (*Envelope, error)

Put sends PUT path with an optional JSON body and returns the envelope.

func (*Client) Request

func (c *Client) Request(ctx context.Context, method, path string, query url.Values, opts WriteOptions) (*Envelope, error)

Request sends any method to path and returns the unwrapped envelope.

type Envelope

type Envelope struct {
	Status  string `json:"status"`
	Message string `json:"message,omitempty"`

	Data json.RawMessage `json:"data,omitempty"`

	Meta      *Meta             `json:"meta,omitempty"`
	ErrorCode string            `json:"error_code,omitempty"`
	Errors    map[string]string `json:"errors,omitempty"`
}

Envelope is the shared v2 response wrapper.

type FlexBool

type FlexBool bool

FlexBool is a bool that also decodes from 1/0 or a quoted bool or number.

func (*FlexBool) UnmarshalJSON

func (b *FlexBool) UnmarshalJSON(raw []byte) error

UnmarshalJSON accepts a bool, a number, either quoted, or null (false).

type FlexInt

type FlexInt int

FlexInt is an int that also decodes from a JSON string; some v2 endpoints send numbers as strings.

func (*FlexInt) UnmarshalJSON

func (n *FlexInt) UnmarshalJSON(b []byte) error

UnmarshalJSON accepts a JSON number, a quoted number, or null (0).

type FlexNum

type FlexNum float64

FlexNum is a float that also decodes from a JSON string. Money uses FlexInt.

func (FlexNum) String

func (n FlexNum) String() string

String renders the value without trailing zeros.

func (*FlexNum) UnmarshalJSON

func (n *FlexNum) UnmarshalJSON(b []byte) error

UnmarshalJSON accepts a JSON number, a quoted number, or null (0).

type HTTPError

type HTTPError struct {
	StatusCode int
	Code       string
	Message    string
	RequestID  string

	// Errors holds 422 field-level messages.
	Errors map[string]string
}

HTTPError is a server-returned error, distinct from a network error.

func (*HTTPError) Error

func (e *HTTPError) Error() string

type Meta

type Meta struct {
	Pagination Pagination `json:"pagination"`
}

Meta holds list-response metadata.

type Pagination

type Pagination struct {
	Total       int  `json:"total"`
	PerPage     int  `json:"per_page"`
	CurrentPage int  `json:"current_page"`
	LastPage    int  `json:"last_page"`
	HasMore     bool `json:"has_more"`
}

Pagination describes a list response's paging state.

func ListInto

func ListInto[T any](env *Envelope) ([]T, *Pagination, error)

ListInto decodes a list envelope's data into []T and returns its pagination (nil when the response carries no meta).

type TransportError added in v0.1.1

type TransportError struct {
	Host    string
	Timeout time.Duration
	Err     error
	// contains filtered or unexported fields
}

TransportError is a request that got no usable answer: the host never replied, or the reply broke off. Unwrap keeps the Go chain (*url.Error, net and TLS errors) reachable for callers that branch on it.

func NewReadError added in v0.1.1

func NewReadError(host string, err error) *TransportError

NewReadError wraps err from reading the body of an answer host had started to send.

func NewTransportError added in v0.1.1

func NewTransportError(host string, timeout time.Duration, err error) *TransportError

NewTransportError wraps err from sending a request to host with a client timeout of timeout.

func (*TransportError) Cancelled added in v0.1.1

func (e *TransportError) Cancelled() bool

Cancelled reports a request stopped by its caller (Ctrl-C), which says nothing about the network.

func (*TransportError) Error added in v0.1.1

func (e *TransportError) Error() string

func (*TransportError) Reason added in v0.1.1

func (e *TransportError) Reason() string

Reason names the cause in plain words, without the Go error chain.

func (*TransportError) Unwrap added in v0.1.1

func (e *TransportError) Unwrap() error

type WriteOptions

type WriteOptions struct {
	// Body is JSON-encoded; a json.RawMessage is sent verbatim.
	Body any
	// IdempotencyKey is sent as X-Idempotency-Key and reused across retries.
	IdempotencyKey string
	// Header is applied after the standard headers, so it can override them.
	Header http.Header
}

WriteOptions configures a mutating request (Post/Put/Delete).

Jump to

Keyboard shortcuts

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