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

neuron

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Dec 22, 2025 License: MIT Imports: 17 Imported by: 1

README ΒΆ

Neuron πŸ•ΈοΈ

GoVersion License Zero Dependencies Go Reference Go Report Card

Neuron is a zero-dependency, high-performance HTTP client library for Go with a focus on developer experience, type safety, and stdlib compatibility. Built by Kolosys for enterprise-grade applications.

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 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 provides a type-safe HTTP client with rate limiting and circuit breaking

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

	// 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
)

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

Jump to

Keyboard shortcuts

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