client

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Jul 29, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package client implements the low-level HTTP mechanics shared by every Lithic domain package: request execution, retries, pagination, error mapping, and webhook verification. Domain packages (in domain/*) import this package; this package never imports a domain package, so the dependency graph stays acyclic. The root package (github.com/iamkanishka/lithic-go) composes Client with every domain resource and re-exports the public types declared here.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BoolParam

func BoolParam(v url.Values, key string, val *bool)

BoolParam sets key in v to val if val is non-nil.

func IntParam

func IntParam(v url.Values, key string, val int)

IntParam sets key in v to val if val is non-zero.

func JoinPath

func JoinPath(parts ...string) string

JoinPath joins path segments with /.

func MapToValues

func MapToValues(m map[string]any) url.Values

MapToValues converts map[string]any string values into url.Values.

func MergeValues

func MergeValues(base, extra url.Values) url.Values

MergeValues merges two url.Values, with extra taking precedence on conflicts.

func NextCursorFromItems

func NextCursorFromItems(items []map[string]any) string

NextCursorFromItems extracts the token of the last item for cursor pagination.

func Ptr

func Ptr[T any](v T) *T

Ptr returns a pointer to v. Convenience for optional fields.

func StringMapToValues

func StringMapToValues(m map[string]string) url.Values

StringMapToValues converts map[string]string into url.Values.

func StringParam

func StringParam(v url.Values, key, val string)

StringParam sets key in v to val if val is non-empty.

func ToInt

func ToInt(v any) int

ToInt safely casts interface{} to int.

func ToString

func ToString(v any) string

ToString safely casts interface{} to string.

func UnmarshalAs

func UnmarshalAs[T any](raw map[string]any) (*T, error)

UnmarshalAs decodes a raw map[string]any into a typed struct T.

Types

type Address

type Address struct {
	Address1   string `json:"address1"`
	Address2   string `json:"address2,omitempty"`
	City       string `json:"city"`
	Country    string `json:"country"`
	PostalCode string `json:"postal_code"`
	State      string `json:"state"`
}

Address is a standard postal address used across several Lithic resources (e.g. card shipping addresses, account verification addresses).

type Client

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

Client is the low-level Lithic HTTP client. It handles authentication, retries, and response decoding, but knows nothing about individual API resources — those live in domain packages that hold a *Client and call its Get/Post/Patch/Put/Delete methods. The root package composes a Client together with every domain resource into the public API.

Create one with New() and reuse it across goroutines — it is safe for concurrent use.

func New

func New(opts ...Option) *Client

New creates a new low-level Lithic client with the given options. If no APIKey is provided via options, LITHIC_API_KEY env var is used.

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, path string) (map[string]any, error)

Delete issues a DELETE request.

func (*Client) Get

func (c *Client) Get(ctx context.Context, path string, params url.Values) (map[string]any, error)

Get issues a GET request.

func (*Client) Patch

func (c *Client) Patch(ctx context.Context, path string, body any) (map[string]any, error)

Patch issues a PATCH request with an auto-generated idempotency key.

func (*Client) Post

func (c *Client) Post(ctx context.Context, path string, body any) (map[string]any, error)

Post issues a POST request with an auto-generated idempotency key.

func (*Client) Put

func (c *Client) Put(ctx context.Context, path string, body any) (map[string]any, error)

Put issues a PUT request with an auto-generated idempotency key.

func (*Client) Status

func (c *Client) Status(ctx context.Context) (map[string]any, error)

Status checks API connectivity.

type Config

type Config struct {
	// APIKey is the Lithic API key. Defaults to LITHIC_API_KEY env var.
	APIKey string

	// Environment selects production or sandbox. Default: production.
	Environment Environment

	// HTTPClient is the underlying HTTP client. Default: http.DefaultClient with 30s timeout.
	HTTPClient *http.Client

	// MaxRetries is the number of retry attempts on 5xx / network errors. Default: 3.
	MaxRetries int

	// RetryBaseDelay is the initial retry backoff. Default: 500ms.
	RetryBaseDelay time.Duration

	// RetryMaxDelay caps exponential backoff. Default: 30s.
	RetryMaxDelay time.Duration

	// DefaultPageSize is used when PageSize is not specified in list requests. Default: 50.
	DefaultPageSize int

	// Logger for diagnostic output. Default: slog.Default().
	Logger *slog.Logger

	// BaseURL overrides the resolved environment URL (useful for testing).
	BaseURL string
}

Config holds all configuration for a Lithic client.

type Environment

type Environment string

Environment selects the Lithic API base URL.

const (
	EnvironmentProduction Environment = "production"
	EnvironmentSandbox    Environment = "sandbox"
)

type Error

type Error struct {
	Category   ErrorCategory
	StatusCode int
	Message    string
	RequestID  string
	Body       map[string]any
}

Error is returned by all Lithic API calls on failure.

func (*Error) Error

func (e *Error) Error() string

func (*Error) IsAuthError

func (e *Error) IsAuthError() bool

IsAuthError reports whether the error is a 401 Unauthorized.

func (*Error) IsNotFound

func (e *Error) IsNotFound() bool

IsNotFound reports whether the error is a 404 Not Found.

func (*Error) IsRateLimit

func (e *Error) IsRateLimit() bool

IsRateLimit reports whether the error is a 429 Too Many Requests.

func (*Error) IsServerError

func (e *Error) IsServerError() bool

IsServerError reports whether the error is a 5xx.

func (*Error) IsValidationError

func (e *Error) IsValidationError() bool

IsValidationError reports whether the error is a 400/422.

type ErrorCategory

type ErrorCategory string

ErrorCategory classifies the source of a Lithic API error.

const (
	ErrorCategoryAPI        ErrorCategory = "api_error"
	ErrorCategoryAuth       ErrorCategory = "auth_error"
	ErrorCategoryValidation ErrorCategory = "validation_error"
	ErrorCategoryNotFound   ErrorCategory = "not_found"
	ErrorCategoryRateLimit  ErrorCategory = "rate_limit"
	ErrorCategoryNetwork    ErrorCategory = "network_error"
	ErrorCategoryConfig     ErrorCategory = "config_error"
	ErrorCategoryDecode     ErrorCategory = "decode_error"
)

type Iter

type Iter[T any] struct {
	Fetch func(ctx context.Context, cursor string) ([]T, string, bool, error)
	// contains filtered or unexported fields
}

Iter is a lazy iterator over all pages of a list endpoint. Usage:

iter := client.Cards.List(ctx, lithic.CardsListParams{})
for iter.Next(ctx) {
    card := iter.Item()
    // use card
}
if err := iter.Err(); err != nil { ... }

func (*Iter[T]) All

func (it *Iter[T]) All(ctx context.Context) ([]T, error)

All collects every item across all pages into a slice.

func (*Iter[T]) Err

func (it *Iter[T]) Err() error

Err returns any iteration error.

func (*Iter[T]) Item

func (it *Iter[T]) Item() T

Item returns the current item.

func (*Iter[T]) Next

func (it *Iter[T]) Next(ctx context.Context) bool

Next advances the iterator. Returns false when done or on error.

type ListParams

type ListParams struct {
	PageSize      int    `url:"page_size,omitempty"`
	StartingAfter string `url:"starting_after,omitempty"`
	EndingBefore  string `url:"ending_before,omitempty"`
}

ListParams holds common pagination parameters for list endpoints. Domain-specific list params embed this and add their own filters.

func (ListParams) ToValues

func (lp ListParams) ToValues() url.Values

ToValues converts the common pagination fields into url.Values.

type Option

type Option func(*Config)

Option is a functional option for configuring a Client.

func WithAPIKey

func WithAPIKey(key string) Option

WithAPIKey sets the API key.

func WithBaseURL

func WithBaseURL(u string) Option

WithBaseURL overrides the API base URL (for testing).

func WithEnvironment

func WithEnvironment(env Environment) Option

WithEnvironment selects production or sandbox.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient sets a custom HTTP client.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets a custom slog.Logger.

func WithMaxRetries

func WithMaxRetries(n int) Option

WithMaxRetries sets the maximum number of retry attempts.

func WithSandbox

func WithSandbox() Option

WithSandbox is a convenience alias for WithEnvironment(EnvironmentSandbox).

type Page

type Page[T any] struct {
	Data    []T  `json:"data"`
	HasMore bool `json:"has_more"`
	// contains filtered or unexported fields
}

Page represents a single page from a Lithic list endpoint.

func (*Page[T]) NextCursor

func (p *Page[T]) NextCursor() string

NextCursor returns the cursor to fetch the next page, or "" if none.

type PageResponse

type PageResponse struct {
	Data    []map[string]any `json:"data"`
	HasMore bool             `json:"has_more"`
}

PageResponse is the raw JSON shape returned by list endpoints.

func PageFromRaw

func PageFromRaw(raw map[string]any) (*PageResponse, error)

PageFromRaw decodes a raw map response into a PageResponse.

type WebhookClient

type WebhookClient struct{}

WebhookClient verifies Lithic webhook signatures. Covers: Event Subscriptions, Auth Stream Access, Tokenization Decisioning, 3DS Decisioning.

func (*WebhookClient) MustVerifyPayload

func (w *WebhookClient) MustVerifyPayload(rawBody []byte, signature, timestamp, secret string) map[string]any

MustVerifyPayload is like VerifyPayload but panics on failure.

func (*WebhookClient) VerifyPayload

func (w *WebhookClient) VerifyPayload(rawBody []byte, signature, timestamp, secret string) (map[string]any, error)

VerifyPayload verifies a Lithic webhook payload and returns the decoded body.

rawBody  — the raw HTTP request body bytes (do not decode before passing)
signature — value of the "webhook-signature" header
timestamp — value of the "webhook-timestamp" header
secret    — the webhook HMAC secret (from GetSubscriptionSecret, GetASASecret, etc.)

func (*WebhookClient) VerifyPayloadWithTolerance

func (w *WebhookClient) VerifyPayloadWithTolerance(rawBody []byte, signature, timestamp, secret string, toleranceSecs int) (map[string]any, error)

VerifyPayloadWithTolerance is like VerifyPayload but with a custom timestamp tolerance in seconds.

Jump to

Keyboard shortcuts

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