proxy

package
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 2026 License: MIT Imports: 16 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const ShadowHeader = "X-Mroki-Mode"

ShadowHeader is the fixed header added to requests forwarded to the shadow service so downstream systems can distinguish shadow traffic from live traffic. The name is intentionally not configurable so consumers can rely on a stable convention. The live request path is never modified.

View Source
const ShadowHeaderValue = "shadow"

ShadowHeaderValue is the value set on ShadowHeader for shadow requests. Consumers can match it to distinguish a shadow request from a live one even when both upstreams share a host (differing only by path or query).

Variables

This section is empty.

Functions

func NewHTTPClient added in v1.6.0

func NewHTTPClient(cfg HTTPClientConfig) *http.Client

NewHTTPClient builds an HTTP client for proxying live and shadow traffic. The connection-pool fields from cfg are applied verbatim; the remaining transport settings (timeouts, keep-alive, HTTP/2) are fixed and not configurable.

func NewProxyResponseDiffer

func NewProxyResponseDiffer(opts ...diff.Option) *proxyResponseDiffer

Types

type CallbackFunc

type CallbackFunc func(req ProxyRequest, live, shadow ProxyResponse) error

type CheckFunc

type CheckFunc func(r *http.Request) bool

CheckFunc returns true if the request should be proxied to shadow

func SamplingRateCheck

func SamplingRateCheck(rate *SamplingRate) CheckFunc

SamplingRateCheck skips shadow based on sampling probability. rate == nil means always sample (always returns true). rate=1.0 and rate=0.0 use fast paths without RNG computation.

func ShadowRulesCheck added in v1.6.0

func ShadowRulesCheck(rules []ShadowRule) CheckFunc

ShadowRulesCheck evaluates an ordered list of shadow rules against incoming requests. Rules are evaluated in definition order; first match wins. Unmatched requests are allowed (shadowed).

type HTTPClientConfig added in v1.6.0

type HTTPClientConfig struct {
	// MaxIdleConns is the maximum number of idle connections across all hosts.
	MaxIdleConns int
	// MaxIdleConnsPerHost is the maximum number of idle connections per host.
	MaxIdleConnsPerHost int
	// MaxConnsPerHost limits the total number of connections per host.
	MaxConnsPerHost int
	// IdleConnTimeout is how long an idle connection is kept before closing.
	IdleConnTimeout time.Duration
}

HTTPClientConfig holds the tunable connection-pool settings for the proxy's HTTP client. Values are applied verbatim by NewHTTPClient — net/http's zero semantics apply (0 means "no limit", or for IdleConnTimeout "no timeout"). This package is intentionally unopinionated: it holds no operational defaults. Callers that need tuned pool sizes (e.g. the proxy binary's config layer) own those defaults and pass them in.

type Option

type Option func(*Proxy)

func WithCallbackFn

func WithCallbackFn(fn CallbackFunc) Option

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient allows setting a custom HTTP client

func WithLiveTimeout

func WithLiveTimeout(timeout time.Duration) Option

WithLiveTimeout sets the timeout for live requests

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger sets the logger for proxy operations

func WithMaxBodySize added in v1.9.0

func WithMaxBodySize(maxBytes int64) Option

WithMaxBodySize sets the maximum request body size (in bytes) that will be buffered for shadow replay. The limit governs shadowing and buffering only — live traffic is always forwarded regardless of size:

  • Requests whose body exceeds the limit are still forwarded to live by streaming (no full-body buffering); shadow and comparison are skipped.
  • Requests with an unknown Content-Length (chunked) are streamed to live while at most maxBytes are buffered for shadow; shadow is skipped if the body turns out to exceed the limit.

A value <= 0 means unlimited: the body is fully buffered and shadow is never skipped for size.

func WithMaxConcurrentCallbacks added in v1.6.0

func WithMaxConcurrentCallbacks(n int) Option

WithMaxConcurrentCallbacks bounds the number of background callback goroutines that may run concurrently. When the limit is reached, further shadow comparisons are dropped (with a warning) instead of spawning unbounded goroutines under load — the live response is unaffected. A value <= 0 leaves the limit unset (unbounded); this package holds no default, so the limit is owned by the caller's config layer.

func WithShadowTimeout

func WithShadowTimeout(timeout time.Duration) Option

WithShadowTimeout sets the timeout for shadow requests

func WithShouldProxyToShadow

func WithShouldProxyToShadow(checks ...CheckFunc) Option

WithShouldProxyToShadow adds check functions to determine if shadow should be proxied Multiple checks can be provided - all must return true (AND logic) Can be called multiple times to add more checks

type Proxy

type Proxy struct {
	Live   *url.URL
	Shadow *url.URL
	// contains filtered or unexported fields
}

func NewProxy

func NewProxy(live, shadow *url.URL, opts ...Option) *Proxy

func (*Proxy) ServeHTTP

func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface for proxying requests.

Request Flow:

  1. Decides shadow eligibility and body handling (see planBody): within-limit bodies are buffered for replay; oversized/unbounded bodies are streamed to live only, without full-body buffering
  2. Launches live request with client context + timeout
  3. Launches shadow request (if sampled) with independent context + timeout
  4. Waits for live response and returns to client immediately
  5. Invokes callback with raw responses in background goroutine

Context Handling:

  • Live requests inherit the client's request context (r.Context()) This means if the client disconnects, live request is cancelled
  • Shadow requests use context.Background() as parent context This makes shadow independent of client connection state, ensuring complete response data collection even if client disconnects
  • Both contexts have their own timeout values for safety

Timeouts:

  • liveTimeout: Controls how long to wait for live service (blocks client)
  • shadowTimeout: Controls how long shadow service can run (doesn't block client)
  • Shadow timeout can be longer since it doesn't impact user experience

type ProxyRequest

type ProxyRequest struct {
	Method   string
	Path     string
	RawQuery string
	Headers  http.Header
	Body     []byte
}

ProxyRequest represents the original HTTP request being proxied

type ProxyResponse

type ProxyResponse struct {
	StatusCode int
	Response   *http.Response
	Body       []byte
	LatencyMs  int64
}

type SamplingRate

type SamplingRate float64

func NewSamplingRate

func NewSamplingRate(rate float64) (*SamplingRate, error)

func (SamplingRate) IsZero

func (s SamplingRate) IsZero() bool

IsZero checks if the sampling rate is zero.

func (SamplingRate) Sample

func (s SamplingRate) Sample() bool

Sample decides whether to sample based on the sampling rate. It returns true if the request should be sampled, false otherwise. Fast paths: rate=1.0 always returns true, rate=0.0 always returns false (no RNG).

func (SamplingRate) String

func (s SamplingRate) String() string

String returns the sampling rate as a formatted string.

type ShadowRule added in v1.6.0

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

ShadowRule is a value object representing a single shadow matching rule. It combines an action (allow/deny), an HTTP method (or "*" for any), and a Caddy-style path pattern.

func BaseShadowRules added in v1.6.0

func BaseShadowRules() []ShadowRule

BaseShadowRules returns the rules that deny non-idempotent methods (POST, PUT, DELETE, PATCH). They are always appended as the final, catch-all entries of the rule list so that the write-protection cannot be accidentally dropped by configuring custom rules. User-supplied rules are evaluated first and can override these per pattern (e.g. "allow POST:/api/v1/search"). GET, HEAD, and OPTIONS requests are shadowed by default.

A fresh slice is returned on each call so callers cannot mutate shared state.

func NewShadowRule added in v1.6.0

func NewShadowRule(action ShadowRuleAction, method, pathPattern string) (ShadowRule, error)

NewShadowRule creates a validated ShadowRule from its components.

func ParseShadowRule added in v1.6.0

func ParseShadowRule(s string) (ShadowRule, error)

ParseShadowRule parses a single rule string of the form "ACTION METHOD:path". Example: "deny POST:*", "allow GET:/api/v1/*".

func ParseShadowRules added in v1.6.0

func ParseShadowRules(s string) ([]ShadowRule, error)

ParseShadowRules parses a comma-separated list of shadow rules. Example: "deny *:/health/*,allow POST:/api/v1/search,deny POST:*"

func (ShadowRule) Action added in v1.6.0

func (r ShadowRule) Action() ShadowRuleAction

Action returns the rule's action.

func (ShadowRule) Matches added in v1.6.0

func (r ShadowRule) Matches(method, reqPath string) bool

Matches reports whether the rule matches the given HTTP method and path.

func (ShadowRule) Method added in v1.6.0

func (r ShadowRule) Method() string

Method returns the rule's HTTP method.

func (ShadowRule) Path added in v1.6.0

func (r ShadowRule) Path() string

Path returns the rule's path pattern.

func (ShadowRule) String added in v1.6.0

func (r ShadowRule) String() string

String returns the rule in its parseable form: "ACTION METHOD:path".

type ShadowRuleAction added in v1.6.0

type ShadowRuleAction string

ShadowRuleAction determines whether a matching request is allowed or denied from being shadowed.

const (
	ShadowRuleAllow ShadowRuleAction = "allow"
	ShadowRuleDeny  ShadowRuleAction = "deny"
)

Jump to

Keyboard shortcuts

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