api

package
v0.0.0-...-7565fcb Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Error types for the AhaSend Go SDK.

Index

Constants

View Source
const (
	// API Authentication
	EnvAPIKey   = "AHASEND_API_KEY"
	EnvAPIToken = "AHASEND_TOKEN" // Alternative to API_KEY

	// Server Configuration
	EnvBaseURL = "AHASEND_BASE_URL"
	EnvHost    = "AHASEND_HOST"   // Host without scheme
	EnvScheme  = "AHASEND_SCHEME" // http or https

	// Debug and Logging
	EnvDebug     = "AHASEND_DEBUG"
	EnvUserAgent = "AHASEND_USER_AGENT"

	// Rate Limiting
	EnvEnableRateLimit = "AHASEND_ENABLE_RATE_LIMIT"
	EnvMaxRetries      = "AHASEND_MAX_RETRIES"

	// Timeouts (in seconds)
	EnvTimeout        = "AHASEND_TIMEOUT"
	EnvConnectTimeout = "AHASEND_CONNECT_TIMEOUT"

	// Idempotency
	EnvIdempotencyAutoGenerate = "AHASEND_IDEMPOTENCY_AUTO_GENERATE"
	EnvIdempotencyPrefix       = "AHASEND_IDEMPOTENCY_PREFIX"
)

Environment variable names

Variables

View Source
var (
	// ContextAccessToken takes a string oauth2 access token as authentication for the request.
	ContextAccessToken = contextKey("accesstoken")

	// ContextServerIndex uses a server configuration from the index.
	ContextServerIndex = contextKey("serverIndex")

	// ContextOperationServerIndices uses a server configuration from the index mapping.
	ContextOperationServerIndices = contextKey("serverOperationIndices")

	// ContextServerVariables overrides a server configuration variables.
	ContextServerVariables = contextKey("serverVariables")

	// ContextOperationServerVariables overrides a server configuration variables using operation specific values.
	ContextOperationServerVariables = contextKey("serverOperationVariables")

	// ContextSkipRateLimit skips rate limiting for this request (used internally by Execute method)
	ContextSkipRateLimit = contextKey("skipRateLimit")

	// ContextIdempotencyKey sets an idempotency key for the request
	ContextIdempotencyKey = contextKey("idempotencyKey")
)

Functions

func ApplyDefaults

func ApplyDefaults(cfg *Configuration)

ApplyDefaults applies default values to a configuration

func ContextWithEnvAuth

func ContextWithEnvAuth(ctx context.Context) context.Context

ContextWithEnvAuth creates a context with API key from environment variables. This is a convenience function for quick setup.

func ExecuteIdempotent

func ExecuteIdempotent[T any](op IdempotentOperation[T], customKey ...string) (T, error)

ExecuteIdempotent executes an idempotent operation with automatic key generation

func GenerateIdempotencyKey

func GenerateIdempotencyKey() string

GenerateIdempotencyKey generates a new UUID-based idempotency key

func GenerateIdempotencyKeyWithPrefix

func GenerateIdempotencyKeyWithPrefix(prefix string) string

GenerateIdempotencyKeyWithPrefix generates a new idempotency key with the given prefix

func GetAPIKeyFromEnv

func GetAPIKeyFromEnv() string

GetAPIKeyFromEnv returns the API key from environment variables. It checks AHASEND_API_KEY first, then falls back to AHASEND_TOKEN.

func GetEnvDocumentation

func GetEnvDocumentation() map[string]string

GetEnvDocumentation returns a list of all supported environment variables with descriptions

func GetTimeoutFromEnv

func GetTimeoutFromEnv() (timeout time.Duration, connectTimeout time.Duration)

GetTimeoutFromEnv returns timeout configuration from environment variables

func IsProductionReady

func IsProductionReady(cfg *Configuration) (bool, []string)

IsProductionReady checks if a configuration is suitable for production use

func LoadEnvIntoConfig

func LoadEnvIntoConfig(cfg *Configuration)

LoadEnvIntoConfig loads environment variables into an existing configuration. This allows you to start with a custom config and overlay environment variables.

func NewValidatedAPIClient

func NewValidatedAPIClient(cfg *Configuration) (*APIClient, ValidationResult)

NewValidatedAPIClient creates a new API client with a validated configuration. Returns the client and any validation results. Deprecated: Use NewAPIClient with functional options instead.

func NewValidatedAPIClientFromEnv

func NewValidatedAPIClientFromEnv() (*APIClient, ValidationResult)

NewValidatedAPIClientFromEnv creates a new API client from environment variables with validation. Returns the client and any validation results.

func NewValidatedConfiguration

func NewValidatedConfiguration() (*Configuration, ValidationResult)

NewValidatedConfiguration creates a new configuration with defaults applied and validation performed

func NewValidatedConfigurationFromEnv

func NewValidatedConfigurationFromEnv() (*Configuration, ValidationResult)

NewValidatedConfigurationFromEnv creates a configuration from environment variables with validation

func OptimizeForProduction

func OptimizeForProduction(cfg *Configuration)

OptimizeForProduction applies production-ready settings to a configuration

func ValidateEnvConfig

func ValidateEnvConfig() []string

ValidateEnvConfig validates environment variables and returns any issues

Types

type APIClient

type APIClient struct {
	APIKeysAPI *APIKeysAPIService

	AccountsAPI *AccountsAPIService

	DomainsAPI *DomainsAPIService

	MessagesAPI *MessagesAPIService

	RoutesAPI *RoutesAPIService

	SMTPCredentialsAPI *SMTPCredentialsAPIService

	StatisticsAPI *StatisticsAPIService

	SubAccountsAPI *SubAccountsAPIService

	SuppressionsAPI *SuppressionsAPIService

	UtilityAPI *UtilityAPIService

	WebhooksAPI *WebhooksAPIService
	// contains filtered or unexported fields
}

APIClient manages communication with the AhaSend API v2 API v2.0.0 In most cases there should be only one, shared, APIClient.

func NewAPIClient

func NewAPIClient(opts ...ClientOption) *APIClient

NewAPIClient creates a new API client with functional options. Example: client := NewAPIClient(WithAPIKey("aha-sk-..."), WithDebug(true))

func NewAPIClientFromEnv

func NewAPIClientFromEnv() *APIClient

NewAPIClientFromEnv creates a new API client with configuration loaded from environment variables. This is the easiest way to get started - just set AHASEND_API_KEY and go.

func NewAPIClientWithConfig

func NewAPIClientWithConfig(cfg *Configuration) *APIClient

NewAPIClientWithConfig creates a new API client with a pre-configured Configuration. This is provided for compatibility with existing validation functions.

func (*APIClient) ConfigureCustomerRateLimits

func (c *APIClient) ConfigureCustomerRateLimits(config CustomerRateLimitConfig)

ConfigureCustomerRateLimits applies a complete customer rate limit configuration This is a convenience method for enterprise customers to set all limits at once

func (*APIClient) EnableRateLimit

func (c *APIClient) EnableRateLimit(endpointType EndpointType, enabled bool)

EnableRateLimit enables or disables rate limiting for a specific endpoint type

func (*APIClient) Execute

func (c *APIClient) Execute(ctx context.Context, config RequestConfig) (*http.Response, error)

Execute is the centralized method for executing all API requests

func (*APIClient) GenerateIdempotencyKey

func (c *APIClient) GenerateIdempotencyKey() string

GenerateIdempotencyKey generates a new UUID-based idempotency key

func (*APIClient) GetConfig

func (c *APIClient) GetConfig() *Configuration

Allow modification of underlying config for alternate implementations and testing Caution: modifying the configuration while live can cause data races and potentially unwanted behavior

func (*APIClient) GetIdempotencyConfig

func (c *APIClient) GetIdempotencyConfig() IdempotencyConfig

GetIdempotencyConfig returns the current idempotency configuration

func (*APIClient) GetRateLimitStatus

func (c *APIClient) GetRateLimitStatus(endpointType EndpointType) RateLimitStatus

GetRateLimitStatus returns the current rate limit status for a specific endpoint type

func (*APIClient) NewIdempotencyKeyBuilder

func (c *APIClient) NewIdempotencyKeyBuilder(baseKey ...string) *IdempotencyKeyBuilder

NewIdempotencyKeyBuilder creates a new idempotency key builder for related operations

func (*APIClient) SetCustomRateLimit

func (c *APIClient) SetCustomRateLimit(endpointType EndpointType, requestsPerSecond, burstCapacity int)

SetCustomRateLimit sets the rate limit for a specific endpoint type

func (*APIClient) SetGeneralRateLimit

func (c *APIClient) SetGeneralRateLimit(requestsPerSecond, burstCapacity int)

SetGeneralRateLimit sets the rate limit for general API endpoints

func (*APIClient) SetGlobalRateLimit

func (c *APIClient) SetGlobalRateLimit(enabled bool)

SetGlobalRateLimit enables or disables rate limiting globally

func (*APIClient) SetIdempotencyConfig

func (c *APIClient) SetIdempotencyConfig(config IdempotencyConfig)

SetIdempotencyConfig updates the idempotency configuration

func (*APIClient) SetSendMessageRateLimit

func (c *APIClient) SetSendMessageRateLimit(requestsPerSecond, burstCapacity int)

SetSendMessageRateLimit sets the rate limit for send message API endpoint

func (*APIClient) SetStatisticsRateLimit

func (c *APIClient) SetStatisticsRateLimit(requestsPerSecond, burstCapacity int)

SetStatisticsRateLimit sets the rate limit for statistics API endpoints

type APIError

type APIError struct {
	Type       ErrorType `json:"-"`
	StatusCode int       `json:"status_code,omitempty"`
	Message    string    `json:"message"`
	Code       string    `json:"code,omitempty"`
	RequestID  string    `json:"request_id,omitempty"`
	RetryAfter int       `json:"retry_after,omitempty"`
	Raw        []byte    `json:"-"`
}

APIError represents an error from the AhaSend API

func ParseAPIError

func ParseAPIError(resp *http.Response, body []byte) *APIError

ParseAPIError creates an APIError from an HTTP response

func (*APIError) Error

func (e *APIError) Error() string

Error implements the error interface

func (*APIError) IsRetryable

func (e *APIError) IsRetryable() bool

IsRetryable returns true if the error is retryable

type APIKeysAPIService

type APIKeysAPIService service

APIKeysAPIService APIKeysAPI service

func (*APIKeysAPIService) CreateAPIKey

func (a *APIKeysAPIService) CreateAPIKey(
	ctx context.Context,
	accountId uuid.UUID,
	request requests.CreateAPIKeyRequest,
	opts ...RequestOption,
) (*responses.APIKey, *http.Response, error)

CreateAPIKey Create API Key

Creates a new API key with the specified scopes

Validation Requirements: - `label` must be provided and non-empty - `scopes` must contain at least one valid scope

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param request CreateAPIKeyRequest - The API key details to create
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return ModelAPIKey, *http.Response, error

func (*APIKeysAPIService) DeleteAPIKey

func (a *APIKeysAPIService) DeleteAPIKey(
	ctx context.Context,
	accountId uuid.UUID,
	keyId uuid.UUID,
	opts ...RequestOption,
) (*common.SuccessResponse, *http.Response, error)

DeleteAPIKey Delete API Key

Deletes an API key

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param keyId API Key ID
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return SuccessResponse, *http.Response, error

func (*APIKeysAPIService) GetAPIKey

func (a *APIKeysAPIService) GetAPIKey(
	ctx context.Context,
	accountId uuid.UUID,
	keyId uuid.UUID,
	opts ...RequestOption,
) (*responses.APIKey, *http.Response, error)

GetAPIKey Get API Key

Returns a specific API key by ID

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param keyId API Key ID
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return ModelAPIKey, *http.Response, error

func (*APIKeysAPIService) GetAPIKeys

GetAPIKeys Get API Keys

Returns a list of API keys for the account

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param pagination Pagination parameters (optional)
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return PaginatedAPIKeysResponse, *http.Response, error

func (*APIKeysAPIService) UpdateAPIKey

func (a *APIKeysAPIService) UpdateAPIKey(
	ctx context.Context,
	accountId uuid.UUID,
	keyId uuid.UUID,
	request requests.UpdateAPIKeyRequest,
	opts ...RequestOption,
) (*responses.APIKey, *http.Response, error)

UpdateAPIKey Update API Key

Updates an existing API key's label and scopes

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param keyId API Key ID
@param request UpdateAPIKeyRequest - The API key details to update
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return ModelAPIKey, *http.Response, error

type AccountsAPIService

type AccountsAPIService service

AccountsAPIService AccountsAPI service

func (*AccountsAPIService) AddAccountMember

func (a *AccountsAPIService) AddAccountMember(
	ctx context.Context,
	accountId uuid.UUID,
	request requests.AddMemberRequest,
	opts ...RequestOption,
) (*responses.UserAccount, *http.Response, error)

AddAccountMember Add Account Member

Adds a new member to the account

Validation Requirements: - `email` must be a valid email address - `role` must be one of: Administrator, Developer, Analyst, Billing Manager

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param request AddMemberRequest - The member details to add
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return UserAccount, *http.Response, error

func (*AccountsAPIService) GetAccount

func (a *AccountsAPIService) GetAccount(
	ctx context.Context,
	accountId uuid.UUID,
	opts ...RequestOption,
) (*responses.Account, *http.Response, error)

GetAccount Get Account

Retrieves detailed information about a specific account

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return Account, *http.Response, error

func (*AccountsAPIService) GetAccountMembers

func (a *AccountsAPIService) GetAccountMembers(
	ctx context.Context,
	accountId uuid.UUID,
	opts ...RequestOption,
) (*responses.AccountMembersResponse, *http.Response, error)

GetAccountMembers Get Account Members

Retrieves a list of all members in the account

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return AccountMembersResponse, *http.Response, error

func (*AccountsAPIService) RemoveAccountMember

func (a *AccountsAPIService) RemoveAccountMember(
	ctx context.Context,
	accountId uuid.UUID,
	userId uuid.UUID,
	opts ...RequestOption,
) (*common.SuccessResponse, *http.Response, error)

RemoveAccountMember Remove Account Member

Removes a member from the account

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param userId User ID to remove
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return SuccessResponse, *http.Response, error

func (*AccountsAPIService) UpdateAccount

func (a *AccountsAPIService) UpdateAccount(
	ctx context.Context,
	accountId uuid.UUID,
	request requests.UpdateAccountRequest,
	opts ...RequestOption,
) (*responses.Account, *http.Response, error)

UpdateAccount Update Account

Updates account information

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param request UpdateAccountRequest - The account details to update
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return Account, *http.Response, error

type BackoffStrategy

type BackoffStrategy string

BackoffStrategy defines the retry backoff strategy

const (
	// BackoffExponential uses exponential backoff with jitter
	BackoffExponential BackoffStrategy = "exponential"
	// BackoffLinear uses linear backoff
	BackoffLinear BackoffStrategy = "linear"
	// BackoffConstant uses constant delay between retries
	BackoffConstant BackoffStrategy = "constant"
)

type ClientOption

type ClientOption func(*Configuration)

ClientOption is a function that modifies a Configuration

func WithAPIKey

func WithAPIKey(key string) ClientOption

WithAPIKey sets the API key for authentication

func WithCustomerRateLimits

func WithCustomerRateLimits(rateLimits CustomerRateLimitConfig) ClientOption

WithCustomerRateLimits sets customer-specific rate limits

func WithDebug

func WithDebug(debug bool) ClientOption

WithDebug enables or disables debug mode

func WithDefaultHeader

func WithDefaultHeader(key, value string) ClientOption

WithDefaultHeader adds a default header to all requests

func WithHTTPClient

func WithHTTPClient(client *http.Client) ClientOption

WithHTTPClient sets a custom HTTP client

func WithIdempotencyConfig

func WithIdempotencyConfig(config IdempotencyConfig) ClientOption

WithIdempotencyConfig sets the idempotency configuration

func WithRateLimit

func WithRateLimit(enabled bool) ClientOption

WithRateLimit enables or disables rate limiting globally

func WithRequestMonitor

func WithRequestMonitor(monitor RequestMonitor) ClientOption

WithRequestMonitor sets a request monitor for observability

func WithRetryConfig

func WithRetryConfig(retryConfig RetryConfig) ClientOption

WithRetryConfig sets the retry configuration

func WithUserAgent

func WithUserAgent(userAgent string) ClientOption

WithUserAgent sets a custom user agent string

type Configuration

type Configuration struct {
	Host             string            `json:"host,omitempty"`
	Scheme           string            `json:"scheme,omitempty"`
	DefaultHeader    map[string]string `json:"defaultHeader,omitempty"`
	UserAgent        string            `json:"userAgent,omitempty"`
	Debug            bool              `json:"debug,omitempty"`
	Servers          ServerConfigurations
	OperationServers map[string]ServerConfigurations
	HTTPClient       *http.Client

	// Authentication configuration
	APIKey string `json:"apiKey,omitempty"`

	// Rate limiting configuration
	EnableRateLimit    bool                     `json:"enableRateLimit,omitempty"`
	CustomerRateLimits *CustomerRateLimitConfig `json:"customerRateLimits,omitempty"`

	// Retry configuration
	RetryConfig RetryConfig `json:"retryConfig"`

	// Default rate limits (can be overridden per customer)
	DefaultGeneralRateLimit     *RateLimitConfig `json:"defaultGeneralRateLimit,omitempty"`
	DefaultStatisticsRateLimit  *RateLimitConfig `json:"defaultStatisticsRateLimit,omitempty"`
	DefaultSendMessageRateLimit *RateLimitConfig `json:"defaultSendMessageRateLimit,omitempty"`

	// Idempotency configuration
	IdempotencyConfig IdempotencyConfig `json:"idempotencyConfig,omitempty"`

	// Monitoring configuration
	RequestMonitor RequestMonitor `json:"-"` // Not serialized - runtime configuration only
}

Configuration stores the configuration of the API client

func ConfigFromEnv

func ConfigFromEnv() *Configuration

ConfigFromEnv creates a new Configuration with values loaded from environment variables. Environment variables override default values but can still be overridden programmatically.

func NewConfiguration

func NewConfiguration() *Configuration

NewConfiguration returns a new Configuration object with default settings

func NewConfigurationFromEnv

func NewConfigurationFromEnv() *Configuration

NewConfigurationFromEnv returns a new Configuration object with values loaded from environment variables. This is a convenience function equivalent to ConfigFromEnv().

func (*Configuration) AddDefaultHeader

func (c *Configuration) AddDefaultHeader(key string, value string)

AddDefaultHeader adds a new HTTP header to the default header in the request

func (*Configuration) ServerURL

func (c *Configuration) ServerURL(index int, variables map[string]string) (string, error)

ServerURL returns URL based on server settings

func (*Configuration) ServerURLWithContext

func (c *Configuration) ServerURLWithContext(ctx context.Context, endpoint string) (string, error)

ServerURLWithContext returns a new server URL given an endpoint

type ConfigurationDefaults

type ConfigurationDefaults struct {
	// Server Configuration
	DefaultHost   string
	DefaultScheme string

	// Client Configuration
	DefaultUserAgent   string
	DefaultDebug       bool
	DefaultTimeout     time.Duration
	DefaultIdleTimeout time.Duration

	// Rate Limiting Defaults
	DefaultEnableRateLimit bool
	DefaultMaxRetries      int

	// Rate Limit Configurations
	DefaultGeneralRPS       int
	DefaultGeneralBurst     int
	DefaultStatisticsRPS    int
	DefaultStatisticsBurst  int
	DefaultSendMessageRPS   int
	DefaultSendMessageBurst int

	// Idempotency Defaults
	DefaultIdempotencyAutoGenerate bool
	DefaultIdempotencyPrefix       string

	// Connection Limits
	DefaultMaxIdleConns        int
	DefaultMaxIdleConnsPerHost int
	DefaultMaxConnsPerHost     int
}

ConfigurationDefaults contains all default values used by the SDK

func GetDefaults

func GetDefaults() ConfigurationDefaults

GetDefaults returns the default configuration values

type ConfigurationSummary

type ConfigurationSummary struct {
	ServerURL          string
	UserAgent          string
	Debug              bool
	MaxRetries         int
	RateLimitEnabled   bool
	IdempotencyEnabled bool
	TimeoutSeconds     int
}

ConfigurationSummary provides a summary of the current configuration

func GetConfigurationSummary

func GetConfigurationSummary(cfg *Configuration) ConfigurationSummary

GetConfigurationSummary returns a summary of the configuration

type ConfigurationValidationError

type ConfigurationValidationError struct {
	Field   string
	Value   interface{}
	Message string
}

ValidationError represents configuration validation errors

func (ConfigurationValidationError) Error

type CustomerRateLimitConfig

type CustomerRateLimitConfig struct {
	General     *RateLimitConfig `json:"general,omitempty"`
	Statistics  *RateLimitConfig `json:"statistics,omitempty"`
	SendMessage *RateLimitConfig `json:"send_message,omitempty"`
}

CustomerRateLimitConfig allows configuring all rate limits at once

type DomainsAPIService

type DomainsAPIService service

DomainsAPIService DomainsAPI service

func (*DomainsAPIService) CheckDomainDNS

func (a *DomainsAPIService) CheckDomainDNS(
	ctx context.Context,
	accountId uuid.UUID,
	domain string,
	opts ...RequestOption,
) (*responses.Domain, *http.Response, error)

CheckDomainDNS Check Domain DNS

Triggers a DNS validation check for the domain. If the domain was checked within the last 60 seconds, the cached validation result is returned instead of performing a fresh lookup.

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param domain Domain name
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return Domain, *http.Response, error

func (*DomainsAPIService) CreateDomain

func (a *DomainsAPIService) CreateDomain(
	ctx context.Context,
	accountId uuid.UUID,
	request requests.CreateDomainRequest,
	opts ...RequestOption,
) (*responses.Domain, *http.Response, error)

CreateDomain Create Domain

Creates a new domain

Validation Requirements: - `domain` must be a valid domain name - `domain` must not already exist in the account - `dkim_private_key` is optional and must be a valid DKIM RSA private key with a minimum key length of 2048 bits if provided.

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param request CreateDomainRequest - The domain details to create
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return Domain, *http.Response, error

func (*DomainsAPIService) DeleteDomain

func (a *DomainsAPIService) DeleteDomain(
	ctx context.Context,
	accountId uuid.UUID,
	domain string,
	opts ...RequestOption,
) (*common.SuccessResponse, *http.Response, error)

DeleteDomain Delete Domain

Deletes a domain

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param domain Domain name
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return SuccessResponse, *http.Response, error

func (*DomainsAPIService) GetDomain

func (a *DomainsAPIService) GetDomain(
	ctx context.Context,
	accountId uuid.UUID,
	domain string,
	opts ...RequestOption,
) (*responses.Domain, *http.Response, error)

GetDomain Get Domain

Returns a specific domain by name

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param domain Domain name
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return Domain, *http.Response, error

func (*DomainsAPIService) GetDomains

func (a *DomainsAPIService) GetDomains(
	ctx context.Context,
	accountId uuid.UUID,
	dnsValid *bool,
	pagination *common.PaginationParams,
	opts ...RequestOption,
) (*responses.PaginatedDomainsResponse, *http.Response, error)

GetDomains Get Domains

Returns a list of domains for the account

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param dnsValid Filter results by DNS validation status (optional)
@param pagination Pagination parameters (optional)
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return PaginatedDomainsResponse, *http.Response, error

func (*DomainsAPIService) UpdateDomain

func (a *DomainsAPIService) UpdateDomain(
	ctx context.Context,
	accountId uuid.UUID,
	domain string,
	request requests.UpdateDomainRequest,
	opts ...RequestOption,
) (*responses.Domain, *http.Response, error)

UpdateDomain Update Domain

Updates DNS domain settings such as custom subdomains and DKIM rotation interval.

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param domain Domain name
@param request UpdateDomainRequest - The domain settings to update
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return Domain, *http.Response, error

type EndpointType

type EndpointType int

EndpointType represents different categories of API endpoints with distinct rate limits

const (
	GeneralAPI     EndpointType = iota // General API endpoints (default: 100 req/s, 200 burst)
	StatisticsAPI                      // Statistics endpoints (default: 1 req/s, 1 burst)
	SendMessageAPI                     // Send message endpoint (default: 100 req/s, 200 burst, often customized)
)

func (EndpointType) String

func (e EndpointType) String() string

String returns the string representation of EndpointType

type EnvConfig

type EnvConfig struct {
	// API Authentication
	APIKey   string `env:"AHASEND_API_KEY" description:"AhaSend API key for authentication"`
	APIToken string `env:"AHASEND_TOKEN" description:"Alternative to AHASEND_API_KEY"`

	// Server Configuration
	BaseURL string `env:"AHASEND_BASE_URL" description:"Full base URL (e.g. https://api.ahasend.com)"`
	Host    string `env:"AHASEND_HOST" description:"API host without scheme (e.g. api.ahasend.com)"`
	Scheme  string `env:"AHASEND_SCHEME" description:"URL scheme: http or https"`

	// Debug and Logging
	Debug     bool   `env:"AHASEND_DEBUG" description:"Enable debug logging"`
	UserAgent string `env:"AHASEND_USER_AGENT" description:"Custom user agent string"`

	// Rate Limiting
	EnableRateLimit bool `env:"AHASEND_ENABLE_RATE_LIMIT" description:"Enable rate limiting"`
	MaxRetries      int  `env:"AHASEND_MAX_RETRIES" description:"Maximum number of retries"`

	// Timeouts
	Timeout        int `env:"AHASEND_TIMEOUT" description:"Request timeout in seconds"`
	ConnectTimeout int `env:"AHASEND_CONNECT_TIMEOUT" description:"Connection timeout in seconds"`

	// Idempotency
	IdempotencyAutoGenerate bool   `env:"AHASEND_IDEMPOTENCY_AUTO_GENERATE" description:"Auto-generate idempotency keys"`
	IdempotencyPrefix       string `env:"AHASEND_IDEMPOTENCY_PREFIX" description:"Prefix for generated idempotency keys"`
}

EnvConfig represents environment variable configuration for documentation

type ErrorType

type ErrorType string

ErrorType represents the category of error

const (
	ErrorTypeAuthentication ErrorType = "authentication"
	ErrorTypePermission     ErrorType = "permission"
	ErrorTypeValidation     ErrorType = "validation"
	ErrorTypeNotFound       ErrorType = "not_found"
	ErrorTypeConflict       ErrorType = "conflict"
	ErrorTypeRateLimit      ErrorType = "rate_limit"
	ErrorTypeIdempotency    ErrorType = "idempotency"
	ErrorTypeServer         ErrorType = "server"
	ErrorTypeNetwork        ErrorType = "network"
	ErrorTypeUnknown        ErrorType = "unknown"
)

type GetWebhooksParams

type GetWebhooksParams struct {
	Enabled              *bool
	OnReception          *bool
	OnDelivered          *bool
	OnTransientError     *bool
	OnFailed             *bool
	OnBounced            *bool
	OnSuppressed         *bool
	OnOpened             *bool
	OnClicked            *bool
	OnSuppressionCreated *bool
	OnDnsError           *bool
	common.PaginationParams
}

type IdempotencyConfig

type IdempotencyConfig struct {
	// AutoGenerate automatically generates UUID idempotency keys when none provided
	AutoGenerate bool
	// KeyPrefix adds a prefix to all generated idempotency keys (optional)
	KeyPrefix string
}

IdempotencyConfig configures idempotency behavior for the SDK

func DefaultIdempotencyConfig

func DefaultIdempotencyConfig() IdempotencyConfig

DefaultIdempotencyConfig returns the default idempotency configuration

type IdempotencyHelper

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

IdempotencyHelper provides convenience methods for idempotent operations

func NewIdempotencyHelper

func NewIdempotencyHelper(config ...IdempotencyConfig) *IdempotencyHelper

NewIdempotencyHelper creates a new idempotency helper with the given config

func (*IdempotencyHelper) EnsureKey

func (h *IdempotencyHelper) EnsureKey(key string) string

EnsureKey returns the provided key or generates a new one if empty

func (*IdempotencyHelper) GenerateKey

func (h *IdempotencyHelper) GenerateKey() string

GenerateKey generates a new idempotency key based on the helper's configuration

type IdempotencyKeyBuilder

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

IdempotencyKeyBuilder helps build deterministic idempotency keys for related operations

func NewIdempotencyKeyBuilder

func NewIdempotencyKeyBuilder(baseKey string) *IdempotencyKeyBuilder

NewIdempotencyKeyBuilder creates a new builder with a base key

func (*IdempotencyKeyBuilder) Next

func (b *IdempotencyKeyBuilder) Next() string

Next returns the next idempotency key in the sequence

func (*IdempotencyKeyBuilder) WithSuffix

func (b *IdempotencyKeyBuilder) WithSuffix(suffix string) string

WithSuffix returns an idempotency key with a specific suffix

type IdempotentOperation

type IdempotentOperation[T any] func(key string) (T, error)

IdempotentOperation represents an operation that can be safely retried

type MessagesAPIService

type MessagesAPIService service

MessagesAPIService MessagesAPI service

func (*MessagesAPIService) CancelMessage

func (a *MessagesAPIService) CancelMessage(
	ctx context.Context,
	accountId uuid.UUID,
	messageId string,
	opts ...RequestOption,
) (*common.SuccessResponse, *http.Response, error)

CancelMessage Cancel Message

Cancels a scheduled message

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param messageId Message ID
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return SuccessResponse, *http.Response, error

func (*MessagesAPIService) CreateConversationMessage

CreateConversationMessage Create Conversational Message

Creates and sends a conversational message with support for To, CC, and BCC recipients.

**Validation Requirements:** - Either `text_content` or `html_content` is required - `from.email` must be from a domain you own with valid DNS records - `to` must contain at least one recipient - The combined `to`, `cc`, and `bcc` recipient count must not exceed 50 - If `reply_to` is provided, do not include `reply-to` in headers - If `cc` is provided, do not include `cc` in headers - `message-id` header will be ignored and automatically generated - Schedule times must be in RFC3339 format - `schedule.first_attempt` must be in the future and within 7 days - `schedule.expires` must be in the future and within 8 days

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param request CreateConversationMessageRequest - The conversational message details to create
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return CreateMessageResponse, *http.Response, error

func (*MessagesAPIService) CreateMessage

CreateMessage Create Message

Creates and sends a message to one or more recipients.

**Validation Requirements:** - Either `text_content` or `html_content` is required - `from.email` must be from a domain you own with valid DNS records - `retention.metadata` must be between 1 and 30 days - `retention.data` must be between 0 and 30 days - If `reply_to` is provided, do not include `reply-to` in headers - `message-id` header will be ignored and automatically generated - Schedule times must be in RFC3339 format - `schedule.first_attempt` must be in the future and within 7 days - `schedule.expires` must be in the future and within 8 days

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param request CreateMessageRequest - The message details to create
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return CreateMessageResponse, *http.Response, error

func (*MessagesAPIService) GetMessage

func (a *MessagesAPIService) GetMessage(
	ctx context.Context,
	accountId uuid.UUID,
	messageId uuid.UUID,
	opts ...RequestOption,
) (*responses.Message, *http.Response, error)

func (*MessagesAPIService) GetMessageByAPIID

func (a *MessagesAPIService) GetMessageByAPIID(
	ctx context.Context,
	accountId uuid.UUID,
	messageId string,
	opts ...RequestOption,
) (*responses.Message, *http.Response, error)

GetMessageByAPIID returns a message by its API ID. messageId can be a bare UUID or a generated Message-ID like <uuid@example.com>.

func (*MessagesAPIService) GetMessages

GetMessages Get Messages

Returns a list of messages for the account. Can be filtered by various parameters.

**Query Parameters:** - `status`: Filter by comma-separated list of message statuses - `tags`: Filter by tags - `sender`: Filter by sender email (must be from domain in API key scopes) - `recipient`: Filter by recipient email - `subject`: Filter by subject text - `message_id_header`: Filter by message ID header (same ID returned by CreateMessage API) - `from_time`: Filter messages created after this time (RFC3339 format) - `to_time`: Filter messages created before this time (RFC3339 format) - `limit`: Maximum number of items to return (1-100, default: 100) - `cursor`: Pagination cursor for the next page (backward compatibility) - `after`: Get items after this cursor (forward pagination) - `before`: Get items before this cursor (backward pagination)

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param params GetMessagesParams - query parameters
@return PaginatedMessagesResponse, *http.Response, error

type NetworkError

type NetworkError struct {
	Op  string // Operation attempted
	Err error  // Underlying error
}

NetworkError represents network-level errors

func (*NetworkError) Error

func (e *NetworkError) Error() string

Error implements the error interface

func (*NetworkError) IsRetryable

func (e *NetworkError) IsRetryable() bool

IsRetryable returns true as network errors are generally retryable

type RateLimitConfig

type RateLimitConfig struct {
	RequestsPerSecond int  `json:"requests_per_second"`
	BurstCapacity     int  `json:"burst_capacity"`
	Enabled           bool `json:"enabled"`
}

RateLimitConfig defines the configuration for a rate limiter

type RateLimitStatus

type RateLimitStatus struct {
	EndpointType      EndpointType `json:"endpoint_type"`
	Enabled           bool         `json:"enabled"`
	RequestsPerSecond int          `json:"requests_per_second"`
	BurstCapacity     int          `json:"burst_capacity"`
	TokensAvailable   int          `json:"tokens_available"`
	NextRefillTime    time.Time    `json:"next_refill_time"`
}

RateLimitStatus provides current status information about a rate limiter

type RateLimiter

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

RateLimiter manages rate limiting for different endpoint types

func NewRateLimiter

func NewRateLimiter() *RateLimiter

NewRateLimiter creates a new rate limiter with default configurations

func (*RateLimiter) ConfigureFromCustomerConfig

func (rl *RateLimiter) ConfigureFromCustomerConfig(config CustomerRateLimitConfig)

ConfigureFromCustomerConfig applies a customer rate limit configuration

func (*RateLimiter) DetectEndpointType

func (rl *RateLimiter) DetectEndpointType(method, path string) EndpointType

DetectEndpointType determines the endpoint type based on HTTP method and path

func (*RateLimiter) EnableRateLimit

func (rl *RateLimiter) EnableRateLimit(endpointType EndpointType, enabled bool)

EnableRateLimit enables or disables rate limiting for a specific endpoint type

func (*RateLimiter) GetBucket

func (rl *RateLimiter) GetBucket(endpointType EndpointType) *TokenBucket

GetBucket returns the appropriate token bucket for the endpoint type

func (*RateLimiter) GetStatus

func (rl *RateLimiter) GetStatus(endpointType EndpointType) RateLimitStatus

GetStatus returns the current status for a specific endpoint type

func (*RateLimiter) IsEnabled

func (rl *RateLimiter) IsEnabled() bool

IsEnabled returns whether rate limiting is globally enabled

func (*RateLimiter) SetGlobalEnabled

func (rl *RateLimiter) SetGlobalEnabled(enabled bool)

SetGlobalEnabled enables or disables rate limiting globally

func (*RateLimiter) SetRateLimit

func (rl *RateLimiter) SetRateLimit(endpointType EndpointType, requestsPerSecond, burstCapacity int)

SetRateLimit updates the rate limit for a specific endpoint type

func (*RateLimiter) WaitForToken

func (rl *RateLimiter) WaitForToken(method, path string) error

WaitForToken blocks until a token is available for the specified request

func (*RateLimiter) WaitForTokenWithContext

func (rl *RateLimiter) WaitForTokenWithContext(ctx context.Context, method, path string) error

WaitForTokenWithContext blocks until a token is available for the specified request, respecting context cancellation

type RequestConfig

type RequestConfig struct {
	// HTTP method (GET, POST, PUT, DELETE, PATCH)
	Method string

	// URL path template with placeholders like "/v2/accounts/{account_id}/messages/{message_id}"
	PathTemplate string

	// Path parameters to replace in template (e.g., {"account_id": "123", "message_id": "456"})
	PathParams map[string]string

	// Query parameters to append to URL
	QueryParams url.Values

	// Additional headers to include (Auth and standard headers added automatically)
	Headers map[string]string

	// Request body (will be JSON encoded if not nil)
	Body interface{}

	// Pointer to result struct where response will be decoded
	Result interface{}

	// Optional: Skip rate limiting for this request
	SkipRateLimit bool

	// Optional: Custom timeout for this specific request
	CustomTimeout *time.Duration

	// Optional: Custom retry configuration for this request
	CustomRetry *RetryConfig
	// contains filtered or unexported fields
}

RequestConfig contains all information needed to execute an API request

type RequestMonitor

type RequestMonitor interface {
	// OnRequestStart is called before a request is sent
	OnRequestStart(ctx context.Context, method, url string, headers map[string]string)
	// OnRequestComplete is called after a request completes (success or failure)
	OnRequestComplete(ctx context.Context, method, url string, statusCode int, duration time.Duration, err error)
	// OnRetry is called when a request is being retried
	OnRetry(ctx context.Context, method, url string, attempt int, err error)
	// OnRateLimitWait is called when a request is delayed due to rate limiting
	OnRateLimitWait(ctx context.Context, endpointType string, waitDuration time.Duration)
}

RequestMonitor provides hooks for monitoring HTTP requests

type RequestOption

type RequestOption func(*RequestConfig)

RequestOption allows modifying RequestConfig using functional options pattern

func WithHeaders

func WithHeaders(headers map[string]string) RequestOption

WithHeaders adds additional headers to the request

func WithIdempotencyKey

func WithIdempotencyKey(key string) RequestOption

WithIdempotencyKey sets an idempotency key for the request

func WithRequestAPIKey

func WithRequestAPIKey(key string) RequestOption

WithRequestAPIKey sets an API key for this specific request (overrides client-level auth)

func WithRetry

func WithRetry(retry RetryConfig) RequestOption

WithRetry sets custom retry configuration for this request

func WithTimeout

func WithTimeout(timeout time.Duration) RequestOption

WithTimeout sets a custom timeout for this specific request

func WithoutRateLimit

func WithoutRateLimit() RequestOption

WithoutRateLimit skips rate limiting for this request

type RetryConfig

type RetryConfig struct {
	// Enabled controls whether retries are enabled at all
	Enabled bool `json:"enabled"`
	// MaxRetries is the maximum number of retry attempts (0 means no retries)
	MaxRetries int `json:"max_retries"`
	// RetryClientErrors controls whether 4xx client errors are retried (default: false)
	RetryClientErrors bool `json:"retry_client_errors"`
	// RetryValidationErrors controls whether client-side validation errors are retried (default: false)
	RetryValidationErrors bool `json:"retry_validation_errors"`
	// BackoffStrategy determines the delay strategy between retries
	BackoffStrategy BackoffStrategy `json:"backoff_strategy"`
	// BaseDelay is the initial delay for the first retry (used by all strategies)
	BaseDelay time.Duration `json:"base_delay"`
	// MaxDelay is the maximum delay between retries (prevents exponential backoff from growing too large)
	MaxDelay time.Duration `json:"max_delay"`
}

RetryConfig provides comprehensive retry configuration options

func DefaultRetryConfig

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig returns sensible default retry configuration

func (RetryConfig) GetDelay

func (rc RetryConfig) GetDelay(attempt int) time.Duration

GetDelay calculates the delay for a specific retry attempt

func (RetryConfig) IsRetryEnabled

func (rc RetryConfig) IsRetryEnabled() bool

IsRetryEnabled returns true if retries are enabled and MaxRetries > 0

type RoutesAPIService

type RoutesAPIService service

RoutesAPIService RoutesAPI service

func (*RoutesAPIService) CreateRoute

func (a *RoutesAPIService) CreateRoute(
	ctx context.Context,
	accountId uuid.UUID,
	request requests.CreateRouteRequest,
	opts ...RequestOption,
) (*responses.Route, *http.Response, error)

CreateRoute Create Route

Creates a new route for inbound email routing

Validation Requirements: - `name` must be a unique route name within the account - `url` must be a valid webhook URL - `recipient` must be a valid inbound route address

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param request CreateRouteRequest - The route details to create
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return Route, *http.Response, error

func (*RoutesAPIService) DeleteRoute

func (a *RoutesAPIService) DeleteRoute(
	ctx context.Context,
	accountId uuid.UUID,
	routeId uuid.UUID,
	opts ...RequestOption,
) (*common.SuccessResponse, *http.Response, error)

DeleteRoute Delete Route

Deletes a route

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param routeId Route ID
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return SuccessResponse, *http.Response, error

func (*RoutesAPIService) GetRoute

func (a *RoutesAPIService) GetRoute(
	ctx context.Context,
	accountId uuid.UUID,
	routeId uuid.UUID,
	opts ...RequestOption,
) (*responses.Route, *http.Response, error)

GetRoute Get Route

Returns a specific route by ID

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param routeId Route ID
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return Route, *http.Response, error

func (*RoutesAPIService) GetRoutes

GetRoutes Get Routes

Returns a list of routes for the account

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param pagination Pagination parameters (optional)
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return PaginatedRoutesResponse, *http.Response, error

func (*RoutesAPIService) GetRoutesWithParams

func (a *RoutesAPIService) GetRoutesWithParams(
	ctx context.Context,
	accountId uuid.UUID,
	params requests.GetRoutesParams,
	opts ...RequestOption,
) (*responses.PaginatedRoutesResponse, *http.Response, error)

GetRoutesWithParams returns routes and supports the domain filter required for domain-scoped route keys.

func (*RoutesAPIService) UpdateRoute

func (a *RoutesAPIService) UpdateRoute(
	ctx context.Context,
	accountId uuid.UUID,
	routeId uuid.UUID,
	request requests.UpdateRouteRequest,
	opts ...RequestOption,
) (*responses.Route, *http.Response, error)

UpdateRoute Update Route

Updates an existing route

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param routeId Route ID
@param request UpdateRouteRequest - The route details to update
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return Route, *http.Response, error

type SMTPCredentialsAPIService

type SMTPCredentialsAPIService service

SMTPCredentialsAPIService SMTPCredentialsAPI service

func (*SMTPCredentialsAPIService) CreateSMTPCredential

CreateSMTPCredential Create SMTP Credential

Creates a new SMTP credential for SMTP authentication

Validation Requirements: - `name` must be a unique credential name within the account - `password` will be auto-generated and returned in the response

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param request CreateSMTPCredentialRequest - The SMTP credential details to create
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return SMTPCredential, *http.Response, error

func (*SMTPCredentialsAPIService) DeleteSMTPCredential

func (a *SMTPCredentialsAPIService) DeleteSMTPCredential(
	ctx context.Context,
	accountId uuid.UUID,
	smtpCredentialId uuid.UUID,
	opts ...RequestOption,
) (*common.SuccessResponse, *http.Response, error)

DeleteSMTPCredential Delete SMTP Credential

Deletes an SMTP credential

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param smtpCredentialId SMTP Credential ID
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return SuccessResponse, *http.Response, error

func (*SMTPCredentialsAPIService) GetSMTPCredential

func (a *SMTPCredentialsAPIService) GetSMTPCredential(
	ctx context.Context,
	accountId uuid.UUID,
	smtpCredentialId uuid.UUID,
	opts ...RequestOption,
) (*responses.SMTPCredential, *http.Response, error)

GetSMTPCredential Get SMTP Credential

Returns a specific SMTP credential by ID

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param smtpCredentialId SMTP Credential ID
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return SMTPCredential, *http.Response, error

func (*SMTPCredentialsAPIService) GetSMTPCredentials

GetSMTPCredentials Get SMTP Credentials

Returns a list of SMTP credentials for the account

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param pagination Pagination parameters (optional)
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return PaginatedSMTPCredentialsResponse, *http.Response, error

type ServerConfiguration

type ServerConfiguration struct {
	URL         string
	Description string
	Variables   map[string]ServerVariable
}

ServerConfiguration stores the information about a server

type ServerConfigurations

type ServerConfigurations []ServerConfiguration

ServerConfigurations stores multiple ServerConfiguration items

func (ServerConfigurations) URL

func (sc ServerConfigurations) URL(index int, variables map[string]string) (string, error)

URL formats template on a index using given variables

type ServerVariable

type ServerVariable struct {
	Description  string
	DefaultValue string
	EnumValues   []string
}

ServerVariable stores the information about a server variable

type StatisticsAPIService

type StatisticsAPIService service

StatisticsAPIService StatisticsAPI service

func (*StatisticsAPIService) GetBounceStatistics

GetBounceStatistics Get Bounce Statistics

Returns transactional bounce statistics grouped by classification

**Query Parameters:** - `from_time`: Filter statistics after this datetime (RFC3339 format) - `to_time`: Filter statistics before this datetime (RFC3339 format) - `sender_domain`: Filter by sender domain - `recipient_domains`: Filter by a comma separated list of recipient domains - `tags`: Filter by tags (comma-separated) - `group_by`: Group by time period (hour, day, week, month)

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param params The query parameters for filtering the statistics
@param opts Optional request options
@return BounceStatisticsResponse

func (*StatisticsAPIService) GetDeliverabilityStatistics

GetDeliverabilityStatistics Get Deliverability Statistics

Returns transactional deliverability statistics grouped by status

**Query Parameters:** - `from_time`: Filter statistics after this datetime (RFC3339 format) - `to_time`: Filter statistics before this datetime (RFC3339 format) - `sender_domain`: Filter by sender domain - `recipient_domains`: Filter by a comma separated list of recipient domains - `tags`: Filter by tags (comma-separated) - `group_by`: Group by time period (hour, day, week, month)

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param params The filtering query params
@param opts Optional request options
@return DeliverabilityStatisticsResponse

func (*StatisticsAPIService) GetDeliveryTimeStatistics

GetDeliveryTimeStatistics Get Delivery Time Statistics

Returns transactional delivery time statistics grouped by recipient domain

**Query Parameters:** - `from_time`: Filter statistics after this datetime (RFC3339 format) - `to_time`: Filter statistics before this datetime (RFC3339 format) - `sender_domain`: Filter by sender domain - `recipient_domains`: Filter by a comma separated list of recipient domains - `tags`: Filter by tags (comma-separated) - `group_by`: Group by time period (hour, day, week, month)

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param params Query parameters for filtering the results
@param opts Optional request options
@return DeliveryTimeStatisticsResponse

type SubAccountsAPIService

type SubAccountsAPIService service

SubAccountsAPIService SubAccountsAPI service

func (*SubAccountsAPIService) CreateSubAccount

func (a *SubAccountsAPIService) CreateSubAccount(
	ctx context.Context,
	accountId uuid.UUID,
	request requests.CreateSubAccountRequest,
	opts ...RequestOption,
) (*responses.SubAccount, *http.Response, error)

CreateSubAccount Create Sub Account

Creates a new sub account under the parent account.

Validation Requirements: - `name` must be provided and non-empty - `website` must be provided and non-empty - `monthly_credit` must be between 0 and 1000000000 when provided

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Parent account ID
@param request CreateSubAccountRequest - The sub-account details to create
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return SubAccount, *http.Response, error

func (*SubAccountsAPIService) CreateSubAccountAPIKey

func (a *SubAccountsAPIService) CreateSubAccountAPIKey(
	ctx context.Context,
	accountId uuid.UUID,
	subAccountId uuid.UUID,
	request requests.CreateAPIKeyRequest,
	opts ...RequestOption,
) (*responses.APIKey, *http.Response, error)

CreateSubAccountAPIKey Create Sub-Account API Key

Creates an API key owned by the sub account. SecretKey is one-time and present only on create responses and exact idempotent replay responses.

Validation Requirements: - `label` must be provided and non-empty - `scopes` must contain at least one valid scope

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Parent account ID
@param subAccountId Sub account ID
@param request CreateAPIKeyRequest - The API key details to create
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return APIKey, *http.Response, error

func (*SubAccountsAPIService) DeleteSubAccount

func (a *SubAccountsAPIService) DeleteSubAccount(
	ctx context.Context,
	accountId uuid.UUID,
	subAccountId uuid.UUID,
	opts ...RequestOption,
) (*common.SuccessResponse, *http.Response, error)

DeleteSubAccount Delete Sub Account

Soft-deletes a sub account under the parent account.

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Parent account ID
@param subAccountId Sub account ID
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return SuccessResponse, *http.Response, error

func (*SubAccountsAPIService) DeleteSubAccountAPIKey

func (a *SubAccountsAPIService) DeleteSubAccountAPIKey(
	ctx context.Context,
	accountId uuid.UUID,
	subAccountId uuid.UUID,
	keyId uuid.UUID,
	opts ...RequestOption,
) (*common.SuccessResponse, *http.Response, error)

DeleteSubAccountAPIKey Delete Sub-Account API Key

Deletes an API key owned by a sub account.

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Parent account ID
@param subAccountId Sub account ID
@param keyId API key ID
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return SuccessResponse, *http.Response, error

func (*SubAccountsAPIService) GetSubAccount

func (a *SubAccountsAPIService) GetSubAccount(
	ctx context.Context,
	accountId uuid.UUID,
	subAccountId uuid.UUID,
	opts ...RequestOption,
) (*responses.SubAccount, *http.Response, error)

GetSubAccount Get Sub Account

Returns a specific sub account under the parent account.

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Parent account ID
@param subAccountId Sub account ID
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return SubAccount, *http.Response, error

func (*SubAccountsAPIService) GetSubAccountAPIKey

func (a *SubAccountsAPIService) GetSubAccountAPIKey(
	ctx context.Context,
	accountId uuid.UUID,
	subAccountId uuid.UUID,
	keyId uuid.UUID,
	opts ...RequestOption,
) (*responses.APIKey, *http.Response, error)

GetSubAccountAPIKey Get Sub-Account API Key

Returns a specific API key owned by a sub account.

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Parent account ID
@param subAccountId Sub account ID
@param keyId API key ID
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return APIKey, *http.Response, error

func (*SubAccountsAPIService) GetSubAccountsUsage

func (a *SubAccountsAPIService) GetSubAccountsUsage(
	ctx context.Context,
	accountId uuid.UUID,
	opts ...RequestOption,
) (*responses.SubAccountUsageResponse, *http.Response, error)

GetSubAccountsUsage Get Sub-Account Usage

Returns current billing-period usage and proportional allocated cost for the parent and active sub accounts.

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Parent account ID
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return SubAccountUsageResponse, *http.Response, error

func (*SubAccountsAPIService) ListSubAccountAPIKeys

func (a *SubAccountsAPIService) ListSubAccountAPIKeys(
	ctx context.Context,
	accountId uuid.UUID,
	subAccountId uuid.UUID,
	pagination *common.PaginationParams,
	opts ...RequestOption,
) (*responses.PaginatedAPIKeysResponse, *http.Response, error)

ListSubAccountAPIKeys List Sub-Account API Keys

Returns a cursor-paginated list of API keys owned by a sub account.

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Parent account ID
@param subAccountId Sub account ID
@param pagination Pagination parameters (optional)
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return PaginatedAPIKeysResponse, *http.Response, error

func (*SubAccountsAPIService) ListSubAccounts

ListSubAccounts List Sub Accounts

Returns a cursor-paginated list of sub accounts under the parent account.

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Parent account ID
@param pagination Pagination parameters (optional)
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return PaginatedSubAccountsResponse, *http.Response, error

func (*SubAccountsAPIService) SuspendSubAccount

func (a *SubAccountsAPIService) SuspendSubAccount(
	ctx context.Context,
	accountId uuid.UUID,
	subAccountId uuid.UUID,
	request requests.SuspendSubAccountRequest,
	opts ...RequestOption,
) (*responses.SubAccount, *http.Response, error)

SuspendSubAccount Suspend Sub Account

Suspends a sub account under the parent account.

Validation Requirements: - `reason` must be provided and non-empty

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Parent account ID
@param subAccountId Sub account ID
@param request SuspendSubAccountRequest - The suspension details
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return SubAccount, *http.Response, error

func (*SubAccountsAPIService) UnsuspendSubAccount

func (a *SubAccountsAPIService) UnsuspendSubAccount(
	ctx context.Context,
	accountId uuid.UUID,
	subAccountId uuid.UUID,
	opts ...RequestOption,
) (*responses.SubAccount, *http.Response, error)

UnsuspendSubAccount Unsuspend Sub Account

Unsuspends a sub account under the parent account.

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Parent account ID
@param subAccountId Sub account ID
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return SubAccount, *http.Response, error

func (*SubAccountsAPIService) UpdateSubAccount

func (a *SubAccountsAPIService) UpdateSubAccount(
	ctx context.Context,
	accountId uuid.UUID,
	subAccountId uuid.UUID,
	request requests.UpdateSubAccountRequest,
	opts ...RequestOption,
) (*responses.SubAccount, *http.Response, error)

UpdateSubAccount Update Sub Account

Updates a sub account's editable settings.

Validation Requirements: - at least one editable field must be provided - `name` and `website` must be non-empty when provided - `monthly_credit` must be between 0 and 1000000000 when provided

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Parent account ID
@param subAccountId Sub account ID
@param request UpdateSubAccountRequest - The sub-account details to update
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return SubAccount, *http.Response, error

func (*SubAccountsAPIService) UpdateSubAccountAPIKey

func (a *SubAccountsAPIService) UpdateSubAccountAPIKey(
	ctx context.Context,
	accountId uuid.UUID,
	subAccountId uuid.UUID,
	keyId uuid.UUID,
	request requests.UpdateAPIKeyRequest,
	opts ...RequestOption,
) (*responses.APIKey, *http.Response, error)

UpdateSubAccountAPIKey Update Sub-Account API Key

Updates the label and scopes for an API key owned by a sub account.

Validation Requirements: - at least one editable field must be provided - `label` must be non-empty when provided - `scopes` must contain at least one valid scope when provided

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Parent account ID
@param subAccountId Sub account ID
@param keyId API key ID
@param request UpdateAPIKeyRequest - The API key details to update
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return APIKey, *http.Response, error

type SuppressionsAPIService

type SuppressionsAPIService service

SuppressionsAPIService SuppressionsAPI service

func (*SuppressionsAPIService) CreateSuppression

CreateSuppression Create Suppression

Creates a new suppression for an email address

Validation Requirements: - `email` must be a valid email address - `expires_at` must be in RFC3339 format - `domain` is optional - if not provided, applies to all account domains

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param request CreateSuppressionRequest - The suppression details to create
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return CreateSuppressionResponse, *http.Response, error

func (*SuppressionsAPIService) DeleteAllSuppressions

func (a *SuppressionsAPIService) DeleteAllSuppressions(
	ctx context.Context,
	accountId uuid.UUID,
	domain *string,
	opts ...RequestOption,
) (*common.SuccessResponse, *http.Response, error)

DeleteAllSuppressions Delete All Suppressions

Deletes all suppressions for the account

Query Parameters: - `domain`: Optional domain filter to delete suppressions for specific domain only

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param domain Optional domain filter (optional)
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return SuccessResponse, *http.Response, error

func (*SuppressionsAPIService) DeleteSuppression

func (a *SuppressionsAPIService) DeleteSuppression(
	ctx context.Context,
	accountId uuid.UUID,
	email string,
	domain *string,
	opts ...RequestOption,
) (*common.SuccessResponse, *http.Response, error)

DeleteSuppression Delete Suppression

Deletes a specific suppression by email address

Query Parameters: - `domain`: Optional domain filter to delete suppression for specific domain only

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param email Email address
@param domain Optional domain filter (optional)
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return SuccessResponse, *http.Response, error

func (*SuppressionsAPIService) GetSuppressions

GetSuppressions Get Suppressions

Returns a list of suppressions for the account

Query Parameters: - `domain`: Filter by domain (optional) - `email`: Filter by email (optional) - `from_time`: Filter suppressions created after this time (RFC3339 format) - `to_time`: Filter suppressions created before this time (RFC3339 format) - `limit`: Maximum number of items to return (1-100, default: 100) - `cursor`: Pagination cursor for the next page (backward compatibility) - `after`: Get items after this cursor (forward pagination) - `before`: Get items before this cursor (backward pagination)

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param params GetSuppressionsParams - query parameters
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return PaginatedSuppressionsResponse, *http.Response, error

type TokenBucket

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

TokenBucket implements a token bucket rate limiter

func NewTokenBucket

func NewTokenBucket(config RateLimitConfig) *TokenBucket

NewTokenBucket creates a new token bucket with the specified configuration

func (*TokenBucket) GetStatus

func (tb *TokenBucket) GetStatus(endpointType EndpointType) RateLimitStatus

GetStatus returns the current status of the token bucket

func (*TokenBucket) UpdateConfig

func (tb *TokenBucket) UpdateConfig(config RateLimitConfig)

UpdateConfig updates the rate limit configuration

func (*TokenBucket) WaitForToken

func (tb *TokenBucket) WaitForToken() error

WaitForToken blocks until a token is available, respecting the rate limit

func (*TokenBucket) WaitForTokenWithContext

func (tb *TokenBucket) WaitForTokenWithContext(ctx context.Context) error

WaitForTokenWithContext blocks until a token is available, respecting the rate limit and context cancellation

type UtilityAPIService

type UtilityAPIService service

UtilityAPIService UtilityAPI service

func (*UtilityAPIService) Ping

Ping Health check endpoint

Health check endpoint that returns a simple pong response

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return SuccessResponse, *http.Response, error

type ValidationResult

type ValidationResult struct {
	Valid    bool
	Errors   []ConfigurationValidationError
	Warnings []string
}

ValidationResult contains the results of configuration validation

func ValidateAndApplyDefaults

func ValidateAndApplyDefaults(cfg *Configuration) ValidationResult

ValidateAndApplyDefaults validates configuration and applies defaults

func ValidateConfiguration

func ValidateConfiguration(cfg *Configuration) ValidationResult

ValidateConfiguration performs comprehensive validation of a Configuration object

func (ValidationResult) Error

func (r ValidationResult) Error() string

Error returns a formatted error message with all validation errors

func (ValidationResult) HasErrors

func (r ValidationResult) HasErrors() bool

HasErrors returns true if there are validation errors

func (ValidationResult) HasWarnings

func (r ValidationResult) HasWarnings() bool

HasWarnings returns true if there are validation warnings

type WebhooksAPIService

type WebhooksAPIService service

WebhooksAPIService WebhooksAPI service

func (*WebhooksAPIService) CreateWebhook

func (a *WebhooksAPIService) CreateWebhook(
	ctx context.Context,
	accountId uuid.UUID,
	request requests.CreateWebhookRequest,
	opts ...RequestOption,
) (*responses.Webhook, *http.Response, error)

CreateWebhook Create Webhook

Creates a new webhook for event notifications

Validation Requirements: - `url` must be a valid HTTPS URL - `scope` must be either `global` or `scoped` - `domains` is required for scoped webhooks

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param request CreateWebhookRequest - The webhook details to create
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return Webhook, *http.Response, error

func (*WebhooksAPIService) DeleteWebhook

func (a *WebhooksAPIService) DeleteWebhook(
	ctx context.Context,
	accountId uuid.UUID,
	webhookId uuid.UUID,
	opts ...RequestOption,
) (*common.SuccessResponse, *http.Response, error)

DeleteWebhook Delete Webhook

Deletes a webhook

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param webhookId Webhook ID
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return SuccessResponse, *http.Response, error

func (*WebhooksAPIService) GetWebhook

func (a *WebhooksAPIService) GetWebhook(
	ctx context.Context,
	accountId uuid.UUID,
	webhookId uuid.UUID,
	opts ...RequestOption,
) (*responses.Webhook, *http.Response, error)

GetWebhook Get Webhook

Returns a specific webhook by ID

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param webhookId Webhook ID
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return Webhook, *http.Response, error

func (*WebhooksAPIService) GetWebhooks

GetWebhooks Get Webhooks

Returns a list of webhooks for the account

**Query Parameters:** - `enabled`: Filter by enabled status - Event filters: `on_reception`, `on_delivered`, `on_transient_error`, `on_failed`, `on_bounced`, `on_suppressed`, `on_opened`, `on_clicked`, `on_suppression_created`, `on_dns_error` - `limit`: Maximum number of items to return (1-100, default: 100) - `cursor`: Pagination cursor for the next page (backward compatibility) - `after`: Get items after this cursor (forward pagination) - `before`: Get items before this cursor (backward pagination)

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param params GetWebhooksParams - query parameters
@return PaginatedWebhooksResponse, *http.Response, error

func (*WebhooksAPIService) UpdateWebhook

func (a *WebhooksAPIService) UpdateWebhook(
	ctx context.Context,
	accountId uuid.UUID,
	webhookId uuid.UUID,
	request requests.UpdateWebhookRequest,
	opts ...RequestOption,
) (*responses.Webhook, *http.Response, error)

UpdateWebhook Update Webhook

Updates an existing webhook

**Note:** The webhook secret is not updatable

@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param accountId Account ID
@param webhookId Webhook ID
@param request UpdateWebhookRequest - The webhook details to update
@param opts ...RequestOption - optional request options (timeout, retry, headers, etc.)
@return Webhook, *http.Response, error

Jump to

Keyboard shortcuts

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