http

package
v0.0.0-...-0e07cd4 Latest Latest
Warning

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

Go to latest
Published: Apr 9, 2026 License: Apache-2.0 Imports: 18 Imported by: 3

Documentation

Overview

THIS FILE IS AUTO-GENERATED - DO NOT EDIT

Package http provides HTTP-specific implementations of x402 components. This includes HTTP-aware clients, services, and facilitator clients.

THIS FILE IS AUTO-GENERATED - DO NOT EDIT

Index

Constants

View Source
const (
	ResultNoPaymentRequired = "no-payment-required"
	ResultPaymentVerified   = "payment-verified"
	ResultPaymentError      = "payment-error"
)

Result type constants

View Source
const DefaultFacilitatorURL = "https://x402.org/facilitator"

DefaultFacilitatorURL is the default public facilitator

View Source
const EVMPaywallTemplate = "" /* 3133431-byte string literal not displayed */

EVMPaywallTemplate is the pre-built EVM paywall template with inlined CSS and JS

View Source
const SVMPaywallTemplate = "" /* 895406-byte string literal not displayed */

SVMPaywallTemplate is the pre-built SVM paywall template with inlined CSS and JS

View Source
const SettlementOverridesHeader = "Settlement-Overrides"

SettlementOverridesHeader is the HTTP header name for settlement overrides. The value is the canonical HTTP header form (Title-Case) so it works correctly with both http.Header methods and direct map access.

Variables

This section is empty.

Functions

func Do

func Do(ctx context.Context, req *http.Request, x402Client *x402HTTPClient) (*http.Response, error)

Do performs an HTTP request with automatic payment handling

func Get

func Get(ctx context.Context, url string, x402Client *x402HTTPClient) (*http.Response, error)

Get performs a GET request with automatic payment handling

func MarshalSettlementOverrides

func MarshalSettlementOverrides(overrides *x402.SettlementOverrides) string

MarshalSettlementOverrides serializes overrides to the JSON string suitable for the SettlementOverridesHeader value. Returns an empty string on marshal failure (which cannot happen for a well-formed SettlementOverrides value).

func NewClient

func NewClient(client *x402.X402Client) *x402HTTPClient

NewClient creates a new HTTP-aware x402 client

func NewServer

func NewServer(routes RoutesConfig, opts ...x402.ResourceServerOption) *x402HTTPResourceServer

NewServer creates a new HTTP resource server

func Newx402HTTPClient

func Newx402HTTPClient(client *x402.X402Client) *x402HTTPClient

Newx402HTTPClient creates a new HTTP-aware x402 client

func Newx402HTTPResourceServer

func Newx402HTTPResourceServer(routes RoutesConfig, opts ...x402.ResourceServerOption) *x402HTTPResourceServer

Newx402HTTPResourceServer creates a new HTTP resource server

func Post

func Post(ctx context.Context, url string, body io.Reader, x402Client *x402HTTPClient) (*http.Response, error)

Post performs a POST request with automatic payment handling

func WrapClient

func WrapClient(client *http.Client, x402Client *x402HTTPClient) *http.Client

WrapClient wraps a standard HTTP client with x402 payment handling

func WrapHTTPClientWithPayment

func WrapHTTPClientWithPayment(client *http.Client, x402Client *x402HTTPClient) *http.Client

WrapHTTPClientWithPayment wraps a standard HTTP client with x402 payment handling This allows transparent payment handling for HTTP requests

func Wrappedx402HTTPResourceServer

func Wrappedx402HTTPResourceServer(routes RoutesConfig, resourceServer *x402.X402ResourceServer) *x402HTTPResourceServer

Wrappedx402HTTPResourceServer wraps an existing resource server with HTTP functionality.

Types

type AuthHeaders

type AuthHeaders struct {
	Verify    map[string]string
	Settle    map[string]string
	Supported map[string]string
	Discovery map[string]string
}

AuthHeaders contains authentication headers for facilitator endpoints

type AuthProvider

type AuthProvider interface {
	// GetAuthHeaders returns authentication headers for each endpoint
	GetAuthHeaders(ctx context.Context) (AuthHeaders, error)
}

AuthProvider generates authentication headers for facilitator requests

type CompiledRoute

type CompiledRoute struct {
	Verb    string
	Regex   *regexp.Regexp
	Config  RouteConfig
	Pattern string
}

CompiledRoute is a parsed route ready for matching

type DynamicPayToFunc

type DynamicPayToFunc func(context.Context, HTTPRequestContext) (string, error)

DynamicPayToFunc is a function that resolves payTo address dynamically based on request context

type DynamicPriceFunc

type DynamicPriceFunc func(context.Context, HTTPRequestContext) (x402.Price, error)

DynamicPriceFunc is a function that resolves price dynamically based on request context

type EVMPaywallHandler

type EVMPaywallHandler struct{}

EVMPaywallHandler generates paywall HTML for EVM-compatible networks (eip155:*).

func (*EVMPaywallHandler) GenerateHTML

func (h *EVMPaywallHandler) GenerateHTML(_ types.PaymentRequirements, paymentRequired types.PaymentRequired, config *PaywallConfig) string

GenerateHTML generates paywall HTML using the built-in EVM template.

func (*EVMPaywallHandler) Supports

func (h *EVMPaywallHandler) Supports(requirement types.PaymentRequirements) bool

Supports returns true for EVM networks (eip155:* CAIP-2 identifiers).

type FacilitatorConfig

type FacilitatorConfig struct {
	// URL is the base URL of the facilitator service
	URL string

	// HTTPClient is the HTTP client to use (optional)
	HTTPClient *http.Client

	// AuthProvider provides authentication headers (optional)
	AuthProvider AuthProvider

	// Timeout for requests (optional, defaults to 30s)
	Timeout time.Duration

	// Identifier for this facilitator (optional)
	Identifier string
}

FacilitatorConfig configures the HTTP facilitator client

type FacilitatorResponseError

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

FacilitatorResponseError indicates a facilitator returned malformed success payload data.

func (*FacilitatorResponseError) Error

func (e *FacilitatorResponseError) Error() string

func (*FacilitatorResponseError) Unwrap

func (e *FacilitatorResponseError) Unwrap() error

type HTTPAdapter

type HTTPAdapter interface {
	GetHeader(name string) string
	GetMethod() string
	GetPath() string
	GetURL() string
	GetAcceptHeader() string
	GetUserAgent() string
}

HTTPAdapter provides framework-agnostic HTTP operations Implement this for each web framework (Gin, Echo, net/http, etc.)

type HTTPClient

type HTTPClient = x402HTTPClient

HTTPClient is an alias for x402HTTPClient

type HTTPFacilitatorClient

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

HTTPFacilitatorClient communicates with remote facilitator services over HTTP Implements FacilitatorClient interface (supports both V1 and V2)

func NewFacilitatorClient

func NewFacilitatorClient(config *FacilitatorConfig) *HTTPFacilitatorClient

NewFacilitatorClient creates a new HTTP facilitator client

func NewHTTPFacilitatorClient

func NewHTTPFacilitatorClient(config *FacilitatorConfig) *HTTPFacilitatorClient

NewHTTPFacilitatorClient creates a new HTTP facilitator client

func (*HTTPFacilitatorClient) GetAuthProvider

func (c *HTTPFacilitatorClient) GetAuthProvider() AuthProvider

GetAuthProvider returns the authentication provider, or nil if not configured.

func (*HTTPFacilitatorClient) GetSupported

GetSupported gets supported payment kinds (shared by both V1 and V2). Retries up to 3 times with exponential backoff on 429 rate limit errors.

func (*HTTPFacilitatorClient) HTTPClient

func (c *HTTPFacilitatorClient) HTTPClient() *http.Client

HTTPClient returns the underlying HTTP client.

func (*HTTPFacilitatorClient) Settle

func (c *HTTPFacilitatorClient) Settle(ctx context.Context, payloadBytes []byte, requirementsBytes []byte) (*x402.SettleResponse, error)

Settle executes a payment (supports both V1 and V2)

func (*HTTPFacilitatorClient) URL

func (c *HTTPFacilitatorClient) URL() string

URL returns the base URL of the facilitator service.

func (*HTTPFacilitatorClient) Verify

func (c *HTTPFacilitatorClient) Verify(ctx context.Context, payloadBytes []byte, requirementsBytes []byte) (*x402.VerifyResponse, error)

Verify checks if a payment is valid (supports both V1 and V2)

type HTTPProcessResult

type HTTPProcessResult struct {
	Type                string
	Response            *HTTPResponseInstructions
	PaymentPayload      *types.PaymentPayload      // V2 only
	PaymentRequirements *types.PaymentRequirements // V2 only
}

HTTPProcessResult indicates the result of processing a payment request

type HTTPRequestContext

type HTTPRequestContext struct {
	Adapter       HTTPAdapter
	Path          string
	Method        string
	PaymentHeader string
	RoutePattern  string
}

HTTPRequestContext encapsulates an HTTP request

type HTTPResponseInstructions

type HTTPResponseInstructions struct {
	Status  int               `json:"status"`
	Headers map[string]string `json:"headers"`
	Body    interface{}       `json:"body,omitempty"`
	IsHTML  bool              `json:"isHtml,omitempty"`
}

HTTPResponseInstructions tells the framework how to respond

type HTTPServer

type HTTPServer = x402HTTPResourceServer

HTTPServer is an alias for x402HTTPResourceServer

type HTTPTransportContext

type HTTPTransportContext struct {
	Request         *HTTPRequestContext
	ResponseBody    []byte
	ResponseHeaders http.Header
}

HTTPTransportContext carries request and response data through settlement processing. ResponseHeaders must be an http.Header — use Header.Get/Del to preserve canonicalization.

type PaymentOption

type PaymentOption struct {
	Scheme            string                 `json:"scheme"`
	PayTo             interface{}            `json:"payTo"` // string or DynamicPayToFunc
	Price             interface{}            `json:"price"` // x402.Price or DynamicPriceFunc
	Network           x402.Network           `json:"network"`
	MaxTimeoutSeconds int                    `json:"maxTimeoutSeconds,omitempty"`
	Extra             map[string]interface{} `json:"extra,omitempty"`
}

PaymentOption represents a single payment option for a route Represents one way a client can pay for access to the resource

type PaymentOptions

type PaymentOptions = []PaymentOption

PaymentOptions is a slice of PaymentOption for convenience

type PaymentRoundTripper

type PaymentRoundTripper struct {
	Transport http.RoundTripper
	// contains filtered or unexported fields
}

PaymentRoundTripper implements http.RoundTripper with x402 payment handling

func (*PaymentRoundTripper) RoundTrip

func (t *PaymentRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper with V1/V2 version detection

type PaywallBuilder

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

PaywallBuilder composes multiple PaywallNetworkHandlers into a single PaywallProvider. Use NewPaywallBuilder to create a builder, add network handlers, and call Build.

func NewPaywallBuilder

func NewPaywallBuilder() *PaywallBuilder

NewPaywallBuilder creates a new PaywallBuilder.

func (*PaywallBuilder) Build

func (b *PaywallBuilder) Build() PaywallProvider

Build creates a PaywallProvider that dispatches to the first matching network handler.

func (*PaywallBuilder) WithConfig

func (b *PaywallBuilder) WithConfig(config *PaywallConfig) *PaywallBuilder

WithConfig sets default paywall configuration for the builder.

func (*PaywallBuilder) WithNetwork

func (b *PaywallBuilder) WithNetwork(handler PaywallNetworkHandler) *PaywallBuilder

WithNetwork adds a network handler to the builder.

type PaywallConfig

type PaywallConfig struct {
	AppName    string `json:"appName,omitempty"`
	CurrentURL string `json:"currentUrl,omitempty"`
	Testnet    bool   `json:"testnet,omitempty"`
}

PaywallConfig configures the HTML paywall for browser requests

type PaywallNetworkHandler

type PaywallNetworkHandler interface {
	// Supports returns true if this handler can generate HTML for the given payment requirement.
	Supports(requirement types.PaymentRequirements) bool

	// GenerateHTML generates the paywall HTML for the given requirement.
	GenerateHTML(requirement types.PaymentRequirements, paymentRequired types.PaymentRequired, config *PaywallConfig) string
}

PaywallNetworkHandler handles paywall HTML generation for a specific network family. Used with PaywallBuilder to compose network-specific handlers into a single PaywallProvider.

type PaywallProvider

type PaywallProvider interface {
	GenerateHTML(paymentRequired types.PaymentRequired, config *PaywallConfig) string
}

PaywallProvider generates HTML for browser-facing 402 responses. Register a custom implementation via RegisterPaywallProvider to override the built-in EVM/SVM templates.

func DefaultPaywallProvider

func DefaultPaywallProvider() PaywallProvider

DefaultPaywallProvider creates a PaywallProvider with built-in EVM and SVM handlers.

type ProcessSettleResult

type ProcessSettleResult struct {
	Success     bool
	Headers     map[string]string
	ErrorReason string
	Transaction string
	Network     x402.Network
	Payer       string
	// Response contains HTTP instructions for the failure case (status 402, body, etc).
	// Set when Success is false; nil when Success is true.
	Response *HTTPResponseInstructions
}

ProcessSettleResult represents the result of settlement processing

type ProtectedRequestHook

type ProtectedRequestHook func(ctx context.Context, reqCtx HTTPRequestContext, routeConfig RouteConfig) (*ProtectedRequestHookResult, error)

ProtectedRequestHook is called on every request to a protected route, before payment processing. It receives the request context and the matched route configuration. Return nil to continue to the next hook or payment flow. Return a result with GrantAccess=true to bypass payment. Return a result with Abort=true to deny the request with a 403 status.

type ProtectedRequestHookResult

type ProtectedRequestHookResult struct {
	// GrantAccess bypasses payment and grants free access to the resource.
	GrantAccess bool
	// Abort denies the request with a 403 status and the provided Reason.
	Abort  bool
	Reason string
}

ProtectedRequestHookResult represents the result of a protected request hook. A nil result means the hook has no opinion and the next hook (or payment flow) should proceed.

type RouteConfig

type RouteConfig struct {
	// Payment options for this route
	Accepts PaymentOptions `json:"accepts"`

	// HTTP-specific metadata
	Resource          string                 `json:"resource,omitempty"`
	Description       string                 `json:"description,omitempty"`
	MimeType          string                 `json:"mimeType,omitempty"`
	CustomPaywallHTML string                 `json:"customPaywallHtml,omitempty"`
	Extensions        map[string]interface{} `json:"extensions,omitempty"`

	// UnpaidResponseBody is an optional callback to generate a custom response for unpaid API requests.
	// For browser requests (Accept: text/html), the paywall HTML takes precedence.
	// If not provided, defaults to { ContentType: "application/json", Body: nil }.
	UnpaidResponseBody UnpaidResponseBodyFunc `json:"-"`
}

RouteConfig defines payment configuration for an HTTP endpoint

type RouteConfigurationError

type RouteConfigurationError struct {
	// Errors contains all validation failures
	Errors []RouteValidationError
}

RouteConfigurationError collects all route validation errors

func (*RouteConfigurationError) Error

func (e *RouteConfigurationError) Error() string

Error returns a formatted error message listing all validation failures

type RouteValidationError

type RouteValidationError struct {
	// RoutePattern is the route pattern (e.g., "GET /api/weather")
	RoutePattern string

	// Scheme is the payment scheme that failed validation
	Scheme string

	// Network is the network that failed validation
	Network x402.Network

	// Reason is the type of validation failure: "missing_scheme" or "missing_facilitator"
	Reason string

	// Message is a human-readable error message
	Message string
}

RouteValidationError represents a single validation failure for a route's payment option

type RoutesConfig

type RoutesConfig map[string]RouteConfig

RoutesConfig maps route patterns to configurations

type SVMPaywallHandler

type SVMPaywallHandler struct{}

SVMPaywallHandler generates paywall HTML for Solana networks (solana:*).

func (*SVMPaywallHandler) GenerateHTML

func (h *SVMPaywallHandler) GenerateHTML(_ types.PaymentRequirements, paymentRequired types.PaymentRequired, config *PaywallConfig) string

GenerateHTML generates paywall HTML using the built-in SVM template.

func (*SVMPaywallHandler) Supports

func (h *SVMPaywallHandler) Supports(requirement types.PaymentRequirements) bool

Supports returns true for Solana networks (solana:* CAIP-2 identifiers).

type UnpaidResponse

type UnpaidResponse struct {
	// ContentType is the content type for the response (e.g., "application/json", "text/plain").
	ContentType string

	// Body is the response body to include in the 402 response.
	Body interface{}
}

UnpaidResponse represents the custom response for unpaid (402) API requests. This allows servers to return preview data, error messages, or other content when a request lacks payment.

type UnpaidResponseBodyFunc

type UnpaidResponseBodyFunc func(ctx context.Context, reqCtx HTTPRequestContext) (*UnpaidResponse, error)

UnpaidResponseBodyFunc generates a custom response for unpaid API requests. It receives the HTTP request context and returns the content type and body for the 402 response.

For browser requests (Accept: text/html), the paywall HTML takes precedence. This callback is only used for API clients.

Args:

ctx: Context for cancellation
reqCtx: HTTP request context

Returns:

UnpaidResponse with ContentType and Body for the 402 response

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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