Help us shape the future of Go! Take the 2026 Go Developer Survey

neuron

package module
v0.8.1 Latest Latest
Warning

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

Go to latest
Published: Aug 14, 2026 License: MIT Imports: 19 Imported by: 1

README

Neuron 🕸️

GoVersion License Go Reference Go Report Card

Neuron is a type-safe HTTP client for Go. The core is the standard library; Ion is an optional circuit breaker you compose in when you want fail-fast around HTTPClient.Do. Built by Kolosys.

Install

go get github.com/kolosys/neuron

Execute

Typed request and response. Neuron serializes the body, runs retries (including 5xx), and materializes TResponse.

client := neuron.NewClient(neuron.ClientOptions{
    BaseURL: "https://api.example.com",
})

route := neuron.NewRoute[CreateUserReq, User](neuron.MethodPOST, "/users")
resp, err := neuron.Execute(client, route, CreateUserReq{Name: "ada"}, nil)
if err != nil {
    log.Fatal(err)
}
fmt.Println(resp.Data.ID)

Convenience methods (Get, Post, Do, DoWithType) go through the same path.

Stream

Stream returns *http.Response with Body still open. You Close it. Use this for SSE and other long-lived LLM responses — Neuron does not parse SSE.

Retries happen only on transport errors before any response exists. Once headers or a body are received, including 5xx, there is no second POST: replaying an LLM stream can duplicate tool calls.

Stream does not apply AdaptiveTimeout. Set http.Client.Timeout to something like 10 minutes, or put a deadline on the request context.

client := neuron.NewClient(neuron.ClientOptions{
    BaseURL: "https://api.example.com",
    HTTPClient: &http.Client{Timeout: 10 * time.Minute},
})

resp, err := neuron.Stream(client, neuron.MethodPOST, "/v1/messages", body, &neuron.RequestOptions{
    Context: ctx,
})
if err != nil {
    log.Fatal(err)
}
defer resp.Body.Close()
io.Copy(os.Stdout, resp.Body)

Optional Ion circuit

Leave Circuit nil for a plain client. Set it to wrap every HTTPClient.Do in circuit.Execute. An open circuit fails fast as ClientError with Type: ErrorTypeCircuit; the Ion *circuit.CircuitError is the cause.

cb := circuit.New("provider",
    circuit.WithFailureThreshold(5),
    circuit.WithRecovery(circuit.RecoveryManual),
)

client := neuron.NewClient(neuron.ClientOptions{
    BaseURL: "https://api.example.com",
    Circuit: cb,
})

Hooks

Request hooks run after the request is built and before Do. Response hooks run after a response is received. Attach them on the client or per request.

client := neuron.NewClient(neuron.ClientOptions{
    BaseURL: "https://api.example.com",
    RequestHooks: []neuron.RequestHook{
        neuron.AddBearerAuth(os.Getenv("API_TOKEN")),
    },
})

_, err := client.Get("/me", &neuron.RequestOptions{
    RequestHooks: []neuron.RequestHook{
        func(req *http.Request) error {
            req.Header.Set("X-Request-ID", id)
            return nil
        },
    },
})

Do not attach body-consuming response hooks to Stream.

Testing with mock/

neuron/mock provides a RoundTripper, rate limiter, auth, and cache fakes plus assertions.

rt := mock.NewMockRoundTripper(nil)
rt.QueueResponse(mock.ResponseConfig{
    StatusCode: 200,
    Body:       []byte(`{"ok":true}`),
})

client := neuron.NewClient(neuron.ClientOptions{
    BaseURL:    "http://api.example.com",
    HTTPClient: &http.Client{Transport: rt},
})

_, err := client.Get("/health")
mock.AssertRequestCount(t, rt, 1)
mock.AssertRequestMethod(t, rt, 0, "GET")

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddAutoMetrics

func AddAutoMetrics() (RequestHook, ResponseHook, func() MetricsSnapshot)

AddAutoMetrics creates a simple metrics middleware that doesn't require a collector

func GenerateDedupeKey

func GenerateDedupeKey(req *http.Request) string

GenerateDedupeKey creates a default deduplication key from a request

func GetRequestID

func GetRequestID(c context.Context) (string, bool)

GetRequestID extracts the request ID from context

func RequestIDFromRequest

func RequestIDFromRequest(req *http.Request) (string, bool)

RequestIDFromRequest extracts the request ID from an HTTP request

func RequestIDFromResponse

func RequestIDFromResponse(resp *http.Response) (string, bool)

RequestIDFromResponse extracts the request ID from an HTTP response

func Stream added in v0.8.0

func Stream[TRequest any](client *Client, method HTTPMethod, path string, request TRequest, options *RequestOptions) (*http.Response, error)

Stream sends an HTTP request and returns the raw response with Body still open. The caller must Close the body.

Unlike Execute, Stream never retries after headers or a body exist — including 5xx. Closing and re-POSTing an LLM stream can duplicate tool calls. Transport errors that occur before any response are retried according to MaxRetries / RequestOptions.Retries.

Stream does not apply AdaptiveTimeout. LLM callers should set http.Client.Timeout (around 10 minutes) or a request context deadline.

func WithRequestID

func WithRequestID(c context.Context, requestID string) context.Context

WithRequestID adds a request ID to the context

Types

type AuthConfig

type AuthConfig struct {
	Type        AuthType
	Token       string
	Username    string
	Password    string
	HeaderName  string
	HeaderValue string
}

AuthConfig configures authentication hooks

type AuthProvider

type AuthProvider interface {
	GetToken(ctx context.Context) (string, error)
	GetAuthHeader(token string) string
}

AuthProvider interface for authentication

type AuthType

type AuthType int

AuthType represents the type of authentication

const (
	AuthTypeBearer AuthType = iota
	AuthTypeAPIKey
	AuthTypeBasic
	AuthTypeCustom
)

type BodyProvider

type BodyProvider interface {
	ContentType() string
	Body() (io.Reader, error)
}

BodyProvider allows custom body serialization

type Cache

type Cache interface {
	Get(key string) (*CacheEntry, bool)
	Set(key string, entry CacheEntry)
	Delete(key string)
	Clear()
}

Cache interface for caching hooks

type CacheEntry

type CacheEntry struct {
	Data       []byte
	Headers    http.Header
	StatusCode int
	Timestamp  time.Time
	TTL        time.Duration
}

CacheEntry represents a cached response

type Client

type Client struct {
	Config ClientOptions

	// Metrics tracking
	Metrics *MetricsCollector
	// contains filtered or unexported fields
}

Client is a type-safe HTTP client with retries and optional rate limiting. Set ClientOptions.Circuit to wrap HTTPClient.Do in an Ion circuit breaker.

func NewClient

func NewClient(options ClientOptions) *Client

NewClient creates a new type-safe HTTP client

func (*Client) Delete

func (c *Client) Delete(path string, opts ...*RequestOptions) (*Response[any], error)

Delete executes a DELETE request and returns the response

func (*Client) Do

func (c *Client) Do(method HTTPMethod, path string, opts ...*RequestOptions) (*Response[any], error)

Do executes an HTTP request with the specified method and returns the response

func (*Client) Get

func (c *Client) Get(path string, opts ...*RequestOptions) (*Response[any], error)

Get executes a GET request and returns the response

func (*Client) GetMetrics

func (c *Client) GetMetrics() MetricsSnapshot

GetMetrics returns current client metrics

func (*Client) Head

func (c *Client) Head(path string, opts ...*RequestOptions) (*Response[any], error)

Head executes a HEAD request and returns the response

func (*Client) Options

func (c *Client) Options(path string, opts ...*RequestOptions) (*Response[any], error)

Options executes an OPTIONS request and returns the response

func (*Client) Patch

func (c *Client) Patch(path string, opts ...*RequestOptions) (*Response[any], error)

Patch executes a PATCH request and returns the response

func (*Client) Post

func (c *Client) Post(path string, opts ...*RequestOptions) (*Response[any], error)

Post executes a POST request and returns the response

func (*Client) Put

func (c *Client) Put(path string, opts ...*RequestOptions) (*Response[any], error)

Put executes a PUT request and returns the response

func (*Client) Shutdown

func (c *Client) Shutdown(timeout time.Duration) error

Shutdown gracefully shuts down the client

type ClientError

type ClientError struct {
	Type       ErrorType
	Message    string
	StatusCode int
	Route      string
	Method     string    // HTTP method
	URL        string    // Full URL
	Attempt    int       // Retry attempt number
	Timestamp  time.Time // When error occurred
	Cause      error
}

Error types for type-safe error handling

func (ClientError) Error

func (e ClientError) Error() string

func (ClientError) Unwrap

func (e ClientError) Unwrap() error

func (ClientError) WithContext

func (e ClientError) WithContext(req *http.Request, attempt int) ClientError

WithContext adds request context information to the error

type ClientOptions

type ClientOptions struct {
	// Base configuration
	BaseURL   string
	UserAgent string
	Headers   http.Header
	Timeout   time.Duration

	// Request handling
	MaxRetries      int
	RetryDelay      time.Duration
	RetryMultiplier float64

	// Hooks
	RequestHooks  []RequestHook
	ResponseHooks []ResponseHook

	// HTTP client
	HTTPClient *http.Client

	// Circuit, if set, wraps HTTPClient.Do in circuit.Execute.
	// An open circuit fails fast as ClientError with Type ErrorTypeCircuit.
	Circuit circuit.CircuitBreaker

	// Resilience configuration
	AdaptiveTimeout bool

	// Rate limiting
	RateLimiter         RateLimiter
	RateLimitUpdater    RateLimitUpdater
	AutoHandleRateLimit bool

	// Deduplication
	Deduplicator *Deduplicator
}

ClientOptions configures the HTTP client behavior

type CompressionConfig

type CompressionConfig struct {
	Type         CompressionType
	Level        int
	MinSize      int
	ContentTypes []string
}

CompressionConfig configures compression middleware

func DefaultCompressionConfig

func DefaultCompressionConfig() CompressionConfig

DefaultCompressionConfig returns a default compression configuration

type CompressionType

type CompressionType int

CompressionType represents the type of compression

const (
	CompressionTypeGzip CompressionType = iota
	CompressionTypeDeflate
	CompressionTypeBrotli
)

type DedupeConfig

type DedupeConfig struct {
	// Enabled enables request deduplication
	Enabled bool

	// WindowSize is the time window for deduplication
	// Requests with the same key within this window will be deduplicated
	WindowSize time.Duration

	// MaxSize is the maximum number of entries in the dedupe cache
	MaxSize int

	// KeyGenerator generates a unique key for a request
	// If nil, defaults to method + URL
	KeyGenerator func(req *http.Request) string
}

DedupeConfig configures request deduplication behavior

func DefaultDedupeConfig

func DefaultDedupeConfig() DedupeConfig

DefaultDedupeConfig returns sensible defaults for deduplication

type DedupeStats

type DedupeStats struct {
	// Deduped is the number of requests that were deduplicated
	Deduped int64

	// Inflight is the current number of in-flight requests
	Inflight int64
}

DedupeStats contains deduplication statistics

type Deduplicator

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

Deduplicator prevents duplicate concurrent requests

func NewDeduplicator

func NewDeduplicator(config DedupeConfig) *Deduplicator

NewDeduplicator creates a new request deduplicator

func (*Deduplicator) Dedupe

func (d *Deduplicator) Dedupe(ctx context.Context, key string, fn func() (*http.Response, error)) (*http.Response, error)

Dedupe executes a request with deduplication If a request with the same key is already in flight, wait for its result

func (*Deduplicator) Stats

func (d *Deduplicator) Stats() DedupeStats

Stats returns deduplication statistics

type Deserializable

type Deserializable interface {
	UnmarshalJSON(data []byte) error
}

Deserializable represents types that can be deserialized from responses

type EmptyRequest

type EmptyRequest struct{}

EmptyRequest represents requests with no body

type EmptyResponse

type EmptyResponse struct{}

EmptyResponse represents responses with no body

type ErrorType

type ErrorType int
const (
	ErrorTypeRequest ErrorType = iota
	ErrorTypeTimeout
	ErrorTypeResponse
	ErrorTypeNetwork
	ErrorTypeAuth
	ErrorTypeRateLimit
	ErrorTypeCircuit
)

type HTTPMethod

type HTTPMethod string

HTTPMethod represents supported HTTP methods

const (
	MethodGET     HTTPMethod = "GET"
	MethodPOST    HTTPMethod = "POST"
	MethodPUT     HTTPMethod = "PUT"
	MethodPATCH   HTTPMethod = "PATCH"
	MethodDELETE  HTTPMethod = "DELETE"
	MethodHEAD    HTTPMethod = "HEAD"
	MethodOPTIONS HTTPMethod = "OPTIONS"
)

type HeaderConfig

type HeaderConfig struct {
	UserAgent     string
	CustomHeaders map[string]string
	RemoveHeaders []string
	AddHeaders    map[string]string
}

HeaderConfig configures header hooks

func DefaultHeaderConfig

func DefaultHeaderConfig() HeaderConfig

DefaultHeaderConfig returns a default header configuration

type HookChain

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

HookChain manages a chain of hook functions This is an optional utility for advanced use cases; most users will use slices directly

func NewHookChain

func NewHookChain() *HookChain

NewHookChain creates a new hook chain

func (*HookChain) AddRequestHook

func (hc *HookChain) AddRequestHook(hook RequestHook) *HookChain

AddRequestHook adds a request hook to the chain

func (*HookChain) AddResponseHook

func (hc *HookChain) AddResponseHook(hook ResponseHook) *HookChain

AddResponseHook adds a response hook to the chain

func (*HookChain) ApplyRequestHooks

func (hc *HookChain) ApplyRequestHooks(req *http.Request) error

ApplyRequestHooks applies all request hooks in order

func (*HookChain) ApplyResponseHooks

func (hc *HookChain) ApplyResponseHooks(resp *http.Response) error

ApplyResponseHooks applies all response hooks in order

type InMemoryCache

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

InMemoryCache provides a simple in-memory cache implementation

func NewInMemoryCache

func NewInMemoryCache() *InMemoryCache

NewInMemoryCache creates a new in-memory cache

func (*InMemoryCache) Clear

func (c *InMemoryCache) Clear()

func (*InMemoryCache) Delete

func (c *InMemoryCache) Delete(key string)

func (*InMemoryCache) Get

func (c *InMemoryCache) Get(key string) (*CacheEntry, bool)

func (*InMemoryCache) Set

func (c *InMemoryCache) Set(key string, entry CacheEntry)

type JSONValidator

type JSONValidator struct{}

JSONValidator provides JSON schema validation

func (*JSONValidator) Validate

func (v *JSONValidator) Validate(data []byte, contentType string) error

type LogLevel

type LogLevel int

LogLevel represents the logging level

const (
	LogLevelDebug LogLevel = iota
	LogLevelInfo
	LogLevelWarn
	LogLevelError
)

type LoggingConfig

type LoggingConfig struct {
	Level       LogLevel
	IncludeBody bool
	MaxBodySize int
	Logger      *log.Logger
}

LoggingConfig configures the logging hooks

func DefaultLoggingConfig

func DefaultLoggingConfig() LoggingConfig

DefaultLoggingConfig returns a default logging configuration

type MetricsCollector

type MetricsCollector struct {

	// Request metrics
	RequestCount  atomic.Int64
	ResponseCount atomic.Int64
	ErrorCount    atomic.Int64

	// Duration metrics
	TotalDuration atomic.Int64 // nanoseconds
	MinDuration   atomic.Int64 // nanoseconds
	MaxDuration   atomic.Int64 // nanoseconds

	// Status code metrics
	StatusCodeCounts map[int]*atomic.Int64

	// Start time for uptime calculation
	StartTime time.Time
	// contains filtered or unexported fields
}

MetricsCollector collects and stores metrics

func NewMetricsCollector

func NewMetricsCollector() *MetricsCollector

NewMetricsCollector creates a new metrics collector

func (*MetricsCollector) GetMetrics

func (m *MetricsCollector) GetMetrics() MetricsSnapshot

GetMetrics returns current metrics

func (*MetricsCollector) RecordRequest

func (m *MetricsCollector) RecordRequest()

RecordRequest records a request metric

func (*MetricsCollector) RecordResponse

func (m *MetricsCollector) RecordResponse(statusCode int, duration time.Duration)

RecordResponse records a response metric

type MetricsSnapshot

type MetricsSnapshot struct {
	RequestCount     int64
	ResponseCount    int64
	ErrorCount       int64
	AverageDuration  time.Duration
	MinDuration      time.Duration
	MaxDuration      time.Duration
	StatusCodeCounts map[int]int64
	Uptime           time.Duration
}

MetricsSnapshot represents a snapshot of metrics at a point in time

func (*MetricsSnapshot) ErrorRate

func (m *MetricsSnapshot) ErrorRate() float64

ErrorRate returns the error rate as a percentage

func (*MetricsSnapshot) RequestsPerSecond

func (m *MetricsSnapshot) RequestsPerSecond() float64

RequestsPerSecond returns the average requests per second

type NoopRateLimitUpdater

type NoopRateLimitUpdater struct{}

NoopRateLimitUpdater is an updater that does nothing

func (*NoopRateLimitUpdater) UpdateFromHeaders

func (n *NoopRateLimitUpdater) UpdateFromHeaders(method, endpoint string, info *RateLimitInfo) error

UpdateFromHeaders does nothing

type NoopRateLimiter

type NoopRateLimiter struct{}

NoopRateLimiter is a rate limiter that allows all requests

func (*NoopRateLimiter) Allow

func (n *NoopRateLimiter) Allow(ctx context.Context, method, endpoint string) bool

Allow always returns true

func (*NoopRateLimiter) Wait

func (n *NoopRateLimiter) Wait(ctx context.Context, method, endpoint string) error

Wait always returns immediately

type RateLimitHandler

type RateLimitHandler interface {
	RateLimiter
	RateLimitUpdater
}

RateLimitHandler combines limiter and updater for full integration

type RateLimitInfo

type RateLimitInfo struct {
	// Limit is the maximum number of requests allowed in the current window
	Limit int

	// Remaining is the number of requests remaining in the current window
	Remaining int

	// Reset is the absolute time when the rate limit resets
	Reset time.Time

	// ResetAfter is the duration until the rate limit resets
	ResetAfter time.Duration

	// Bucket is the rate limit bucket identifier (Discord-style)
	Bucket string

	// Global indicates if this is a global rate limit
	Global bool

	// RetryAfter is the duration to wait before retrying (from Retry-After header)
	RetryAfter time.Duration

	// Scope indicates the rate limit scope (user, global, shared)
	Scope string
}

RateLimitInfo contains parsed rate limit information from response headers

func ParseRateLimitHeaders

func ParseRateLimitHeaders(headers http.Header) *RateLimitInfo

ParseRateLimitHeaders extracts rate limit info from HTTP response headers Supports standard rate limit headers and Discord-style bucket headers

func (*RateLimitInfo) IsExhausted

func (r *RateLimitInfo) IsExhausted() bool

IsExhausted returns true if the rate limit has been exhausted

func (*RateLimitInfo) WaitDuration

func (r *RateLimitInfo) WaitDuration() time.Duration

WaitDuration returns how long to wait before the next request

type RateLimitUpdater

type RateLimitUpdater interface {
	// UpdateFromHeaders updates rate limit state from response headers
	UpdateFromHeaders(method, endpoint string, info *RateLimitInfo) error
}

RateLimitUpdater receives rate limit info from response headers

type RateLimiter

type RateLimiter interface {
	// Allow checks if a request is allowed without blocking
	// Returns true if the request can proceed immediately
	Allow(ctx context.Context, method, endpoint string) bool

	// Wait blocks until the request is allowed or context is cancelled
	Wait(ctx context.Context, method, endpoint string) error
}

RateLimiter is the interface for rate limiting requests

type RequestHook

type RequestHook func(req *http.Request) error

RequestHook processes requests before they are sent

func AddAPIKeyAuth

func AddAPIKeyAuth(apiKey, headerName string) RequestHook

AddAPIKeyAuth creates an API key authentication hook

func AddAPIKeyHeaderAuth

func AddAPIKeyHeaderAuth(apiKey string) RequestHook

AddAPIKeyHeaderAuth creates an API key authentication middleware with common header names

func AddAccept

func AddAccept(accept string) RequestHook

AddAccept creates an accept header middleware

func AddAuth

func AddAuth(config AuthConfig) RequestHook

AddAuth creates an authentication hook based on configuration

func AddAuthHeader

func AddAuthHeader(header, value string) RequestHook

AddAuthHeader creates a generic header-based authentication hook

func AddAuthentication

func AddAuthentication(authProvider AuthProvider) RequestHook

AddAuthentication adds authentication headers using an AuthProvider

func AddAutoCompression

func AddAutoCompression() RequestHook

AddAutoCompression creates an automatic compression middleware

func AddBasicAuth

func AddBasicAuth(username, password string) RequestHook

AddBasicAuth creates a Basic authentication hook

func AddBearerAuth

func AddBearerAuth(token string) RequestHook

AddBearerAuth creates a Bearer token authentication hook

func AddCompression

func AddCompression(config CompressionConfig) RequestHook

AddCompression creates a request compression middleware

func AddCompressionLevel

func AddCompressionLevel(level int) RequestHook

AddCompressionLevel creates a compression level middleware

func AddContentType

func AddContentType(contentType string) RequestHook

AddContentType creates a content type middleware

func AddCorrelationID

func AddCorrelationID(config RequestIDConfig) RequestHook

AddCorrelationID creates a correlation ID middleware for distributed tracing

func AddDebugLogging

func AddDebugLogging(config LoggingConfig) RequestHook

AddDebugLogging creates a debug logging middleware with detailed information

func AddHeader

func AddHeader(config HeaderConfig) RequestHook

AddHeader creates a header hook based on configuration

func AddHeaderSet

func AddHeaderSet(key, value string) RequestHook

AddHeaderSet creates a middleware that sets a single header

func AddLogging

func AddLogging(config LoggingConfig) RequestHook

AddLogging creates a logging hook

func AddMetrics

func AddMetrics(collector *MetricsCollector) RequestHook

AddMetrics creates a metrics collection middleware

func AddNoCache

func AddNoCache() RequestHook

AddNoCache creates a no-cache middleware

func AddRequestID

func AddRequestID(config RequestIDConfig) RequestHook

AddRequestID creates a request ID middleware

func AddSecurityHeaders

func AddSecurityHeaders() RequestHook

AddSecurityHeaders creates a security headers middleware

func AddStructuredLogging

func AddStructuredLogging(config LoggingConfig) RequestHook

AddStructuredLogging creates a structured logging middleware

func AddTracing

func AddTracing(config RequestIDConfig) RequestHook

AddTracing creates a tracing middleware that propagates request ID

func AddUserAgent

func AddUserAgent(userAgent string) RequestHook

AddUserAgent creates a user agent middleware

func AddValidation

func AddValidation(validator Validator) RequestHook

AddValidation validates request payloads

type RequestIDConfig

type RequestIDConfig struct {
	Generator  RequestIDGenerator
	HeaderName string
	ContextKey any
	Propagate  bool
}

RequestIDConfig configures request ID generation

func DefaultRequestIDConfig

func DefaultRequestIDConfig() RequestIDConfig

DefaultRequestIDConfig returns a default request ID configuration

type RequestIDGenerator

type RequestIDGenerator interface {
	Generate() string
}

RequestIDGenerator generates unique request IDs

type RequestMetrics

type RequestMetrics struct {
	TotalRequests       int64
	SuccessfulRequests  int64
	FailedRequests      int64
	AverageResponseTime time.Duration
}

RequestMetrics provides a snapshot of insights into request performance

type RequestOptions

type RequestOptions struct {
	Headers http.Header
	Query   map[string]any
	Timeout *time.Duration
	Context context.Context
	Retries *int
	Body    any // Request body (JSON, form data, io.Reader, BodyProvider)

	// Per-request hooks (runs after client-level hooks)
	RequestHooks  []RequestHook
	ResponseHooks []ResponseHook

	// IdempotencyKey is used for request deduplication
	// If set, concurrent requests with the same key will share the response
	IdempotencyKey string

	// DisableDedupe skips deduplication for this request
	DisableDedupe bool
}

RequestOptions contains configuration for individual requests

type Response

type Response[T any] struct {
	Data       T
	StatusCode int
	Headers    http.Header
	Raw        *http.Response
	// contains filtered or unexported fields
}

Response wraps HTTP response data with type safety

func DoWithType

func DoWithType[T any](client *Client, method HTTPMethod, path string, opts ...*RequestOptions) (*Response[T], error)

DoWithType executes a request and unmarshals the response to the specified type

func Execute

func Execute[TRequest any, TResponse any](
	client *Client,
	route Route[TRequest, TResponse],
	request TRequest,
	options *RequestOptions,
) (*Response[TResponse], error)

Execute performs a type-safe HTTP request

func (*Response[T]) Bytes

func (r *Response[T]) Bytes() ([]byte, error)

Bytes returns the response body as bytes

func (*Response[T]) IsClientError

func (r *Response[T]) IsClientError() bool

IsClientError returns true if the status code is in the 4xx range

func (*Response[T]) IsError

func (r *Response[T]) IsError() bool

IsError returns true if the status code is 4xx or 5xx

func (*Response[T]) IsServerError

func (r *Response[T]) IsServerError() bool

IsServerError returns true if the status code is in the 5xx range

func (*Response[T]) IsSuccess

func (r *Response[T]) IsSuccess() bool

IsSuccess returns true if the status code is in the 2xx range

func (*Response[T]) JSON

func (r *Response[T]) JSON(target any) error

JSON unmarshals the response body as JSON

func (*Response[T]) String

func (r *Response[T]) String() (string, error)

String returns the response body as a string

type ResponseHook

type ResponseHook func(resp *http.Response) error

ResponseHook processes responses after they are received

func AddRateLimitHandler

func AddRateLimitHandler(updater RateLimitUpdater) ResponseHook

AddRateLimitHandler creates a response hook that parses rate limit headers and updates the provided RateLimitUpdater with the current rate limit state.

func AddRateLimitLogging

func AddRateLimitLogging(logFn func(method, path string, info *RateLimitInfo)) ResponseHook

AddRateLimitLogging creates a response hook that logs rate limit information. The logFn receives the method, path, and parsed rate limit info.

func AddRateLimitRetry

func AddRateLimitRetry() ResponseHook

AddRateLimitRetry creates a response hook that returns an error on 429 responses. The error can be used to trigger automatic retry logic at the client level. For automatic 429 handling, use ClientOptions.AutoHandleRateLimit instead.

func AddResponseCache

func AddResponseCache(cache Cache) ResponseHook

AddResponseCache implements response caching

func AddResponseCompression

func AddResponseCompression(config CompressionConfig) ResponseHook

AddResponseCompression creates a response compression middleware

func AddResponseDebug

func AddResponseDebug(config LoggingConfig) ResponseHook

AddResponseDebug creates a debug response logging middleware

func AddResponseDecompression

func AddResponseDecompression() ResponseHook

AddResponseDecompression creates a response decompression middleware

func AddResponseErrorLogging

func AddResponseErrorLogging(config LoggingConfig) ResponseHook

AddResponseErrorLogging creates an error logging middleware

func AddResponseLogging

func AddResponseLogging(config LoggingConfig) ResponseHook

AddResponseLogging creates a response logging middleware

func AddResponseMetrics

func AddResponseMetrics(collector *MetricsCollector) ResponseHook

AddResponseMetrics creates a response metrics collection middleware

func AddResponseRequestID

func AddResponseRequestID(config RequestIDConfig) ResponseHook

AddResponseRequestID creates a response middleware that logs request ID

func AddResponseStructured

func AddResponseStructured(config LoggingConfig) ResponseHook

AddResponseStructured creates a structured response logging middleware

func AddResponseTimeout

func AddResponseTimeout(timeout time.Duration) ResponseHook

AddResponseTimeout creates a response timeout middleware that checks if a request took too long.

type Route

type Route[TRequest, TResponse any] struct {
	Method HTTPMethod
	Path   string
}

Route represents a type-safe route definition

func NewRoute

func NewRoute[TRequest, TResponse any](method HTTPMethod, path string) Route[TRequest, TResponse]

NewRoute creates a new type-safe route

type SequentialGenerator

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

SequentialGenerator generates sequential request IDs

func (*SequentialGenerator) Generate

func (g *SequentialGenerator) Generate() string

Generate creates a sequential request ID

type Serializable

type Serializable interface {
	MarshalJSON() ([]byte, error)
}

Serializable represents types that can be serialized for requests

type StaticAuthProvider

type StaticAuthProvider struct {
	Token  string
	Prefix string
}

StaticAuthProvider provides static token authentication

func (*StaticAuthProvider) GetAuthHeader

func (a *StaticAuthProvider) GetAuthHeader(token string) string

func (*StaticAuthProvider) GetToken

func (a *StaticAuthProvider) GetToken(ctx context.Context) (string, error)

type TimestampGenerator

type TimestampGenerator struct{}

TimestampGenerator generates timestamp-based request IDs

func (*TimestampGenerator) Generate

func (g *TimestampGenerator) Generate() string

Generate creates a timestamp-based request ID

type UUIDGenerator

type UUIDGenerator struct{}

UUIDGenerator generates UUID-style request IDs

func (*UUIDGenerator) Generate

func (g *UUIDGenerator) Generate() string

Generate creates a new UUID-style request ID

type Validator

type Validator interface {
	Validate(data []byte, contentType string) error
}

Validator interface for request validation

Directories

Path Synopsis
cmd
neuron-cli command
internal
Package mock provides testing utilities and mocks for the neuron HTTP client library.
Package mock provides testing utilities and mocks for the neuron HTTP client library.

Jump to

Keyboard shortcuts

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