Skip to main content

pkg/gateway/config/config.go

Source

Overview

What: Defines the gateway's configuration schema (Go structs + YAML tags), default values, YAML decoding, environment-variable overrides, normalization, and semantic validation.

Why:

The gateway needs one source of truth for configuration shared across:

  • the CLI (cmd/apigw)
  • the runtime (pkg/gateway/runtime)
  • downstream SDK consumers (who reuse the config schema)

Centralizing defaults and validation here avoids "magic values" spread across the codebase and turns configuration mistakes into early, actionable errors.

How:

Load() applies configuration layers in order:

  1. Default() (baseline values)
  2. optional YAML file(s)
  3. environment overrides (secrets/platform knobs/legacy env config)
  4. normalize() (fill missing defaults + canonicalize fields)
  5. Validate() (semantic checks)

Notes: Security: secrets (JWT/webhook/admin) typically come from env vars. Treat rendered configs as sensitive and avoid logging secrets.

Contents

Imports

import block 1

pkg/gateway/config/config.go#L7
import (
"errors"
"fmt"
"net/netip"
"net/url"
"os"
"strconv"
"strings"
"time"

"gopkg.in/yaml.v3"
)

Constants

const block 1

pkg/gateway/config/config.go#L20
const (
defaultPort = 8080
defaultShutdownTimeout = 15 * time.Second
defaultReadinessTimeout = 2 * time.Second
defaultReadinessUserAgent = "api-router-gateway/readyz"
defaultHealthPath = "/health"
defaultRateLimitWindow = 60 * time.Second
defaultRateLimitMax = 120
defaultMetricsEnabled = true
defaultAdminListen = "127.0.0.1:9090"
defaultWebSocketMaxConcurrent = 0
defaultWebSocketIdleTimeout = 5 * time.Minute
defaultConfigEnvVar = "APIGW_CONFIG"
defaultWebhookSignatureHeader = "X-Webhook-Signature"
defaultWebhookMaxAttempts = 3
defaultWebhookBackoff = 2 * time.Second
defaultWebhookTimeout = 10 * time.Second
envTradePrefix = "TRADE"
envTaskPrefix = "TASK"
envPort = "PORT"
envShutdownTimeout = "SHUTDOWN_TIMEOUT_MS"
envReadinessTimeout = "READINESS_TIMEOUT_MS"
envReadinessUserAgent = "READINESS_USER_AGENT"
envGitSHA = "GIT_SHA"
envJWTSecret = "JWT_SECRET"
envJWTAudience = "JWT_AUDIENCE"
envJWTIssuer = "JWT_ISSUER"
envCorsAllowedOrigins = "CORS_ALLOWED_ORIGINS"
envRateLimitWindow = "RATE_LIMIT_WINDOW_MS"
envRateLimitMax = "RATE_LIMIT_MAX"
envMetricsEnabled = "METRICS_ENABLED"
envAdminEnabled = "ADMIN_ENABLED"
envAdminListen = "ADMIN_LISTEN"
envAdminToken = "ADMIN_TOKEN"
envAdminAllow = "ADMIN_ALLOW"
envTLSInsecureSkipVerify = "_TLS_INSECURE_SKIP_VERIFY"
envTLSEnabled = "_TLS_ENABLED"
envTLSCAFile = "_TLS_CA_FILE"
envTLSCertFile = "_TLS_CERT_FILE"
envTLSKeyFile = "_TLS_KEY_FILE"
envAPIURL = "_API_URL"
envHealthPath = "_HEALTH_PATH"
)

defaultPort

What: Default public HTTP listen port (8080).

Why: Common convention for services in local development and containers.

How: Used in Default() and by normalize() when http.port is 0.

defaultShutdownTimeout

What: Default graceful shutdown timeout for the HTTP server.

Why: Avoids indefinite shutdown hangs while giving in-flight requests time to finish.

How: Used in Default() and by normalize() when http.shutdownTimeout is unset/invalid.

defaultReadinessTimeout

What: Default timeout for readiness probe HTTP calls.

Why: Prevents readiness checks from hanging indefinitely and stalling rollouts.

How: Used in Default() and by normalize() when readiness.timeout is unset/invalid.

defaultReadinessUserAgent

What: Default User-Agent header used for readiness probe requests.

Why: Makes readiness traffic identifiable in upstream access logs.

How: Defaulted in Default()/normalize() and used by the readiness checker HTTP client.

defaultHealthPath

What: Default upstream health check path (/health) used for readiness probing.

Why: Ensures upstream readiness checks have a predictable path if omitted.

How: Used in Default() and reinforced by normalize() (including leading-slash canonicalization).

defaultRateLimitWindow

What: Default duration of the rate-limit window.

Why: Pairs with defaultRateLimitMax to define a complete baseline policy.

How: Used in Default() and by normalize() when rateLimit.window is unset/invalid.

defaultRateLimitMax

What: Default maximum number of requests allowed per rate-limit window.

Why: Provides a safe baseline throttle policy when operators enable rate limiting but omit tuning.

How: Used in Default() and by normalize() when rateLimit.max is unset/invalid.

defaultMetricsEnabled

What: Default toggle for metrics exposure.

Why: Metrics are expected in most environments for debugging and alerting.

How: Set by Default(); overridden by YAML/env; consumed by runtime/server wiring.

defaultAdminListen

What: Default listen address for the admin control-plane server.

Why: Binds to loopback by default to reduce accidental exposure of control endpoints.

How: Applied by normalize() when admin.listen is empty.

defaultWebSocketMaxConcurrent

What: Default maximum number of concurrent WebSocket upgrades (0 = unlimited).

Why: Keeps default behavior backwards compatible while enabling operators to add capacity protection.

How: Defaulted in Default()/normalize() and enforced by server middleware prior to upgrade.

defaultWebSocketIdleTimeout

What: Default idle timeout for WebSocket connections (when idle enforcement is enabled).

Why: Protects the gateway from leaked/abandoned upgraded connections consuming resources indefinitely.

How: Defaulted in Default()/normalize() and enforced by the server by wrapping hijacked net.Conn read/write deadlines.

defaultConfigEnvVar

What: Environment variable name (APIGW_CONFIG) that points to a default YAML config file path.

Why: Allows deployments to define a canonical config path without always passing CLI flags.

How: Reads os.Getenv(defaultConfigEnvVar) inside Load() and tries it as an additional YAML input (before WithPath(...) options).

defaultWebhookSignatureHeader

What: Default header name that carries the webhook HMAC signature (X-Webhook-Signature).

Why: Provides a consistent default while allowing per-endpoint override when upstreams differ.

How: Applied by normalize() when webhooks.endpoints[].signatureHeader is empty.

defaultWebhookMaxAttempts

What: Default maximum number of webhook forwarding attempts.

Why: Bounds work per incoming webhook request and limits tail latency.

How: Applied by normalize() when webhooks.endpoints[].maxAttempts is unset/invalid.

defaultWebhookBackoff

What: Default initial backoff duration between webhook delivery attempts.

Why: Avoids immediate retry storms on transient upstream failures.

How: Applied by normalize() when webhooks.endpoints[].initialBackoff is unset/invalid.

defaultWebhookTimeout

What: Default timeout for a single webhook forwarding attempt.

Why: Prevents slow webhook targets from tying up gateway resources indefinitely.

How: Applied by normalize() when webhooks.endpoints[].timeout is unset/invalid.

envTradePrefix

What: Prefix (TRADE) used to build trade upstream env var names.

Why: Keeps upstream env overrides consistent for supported products.

How: Used by applyEnvOverrides()/applyUpstreamOverrides() to locate trade upstream overrides.

envTaskPrefix

What: Prefix (TASK) used to build task upstream env var names.

Why: Keeps upstream env overrides consistent for supported products.

How: Used by applyEnvOverrides()/applyUpstreamOverrides() to locate task upstream overrides.

envPort

What: Env var (PORT) overriding the public HTTP listen port.

Why: Common convention on PaaS platforms where the platform assigns a port.

How: Parsed by applyEnvOverrides() as an integer into http.port.

envShutdownTimeout

What: Env var (SHUTDOWN_TIMEOUT_MS) overriding http.shutdownTimeout (milliseconds).

Why: Shutdown grace needs may vary by environment and traffic patterns.

How: Parsed by applyEnvOverrides() via parsePositiveDurationMillis.

envReadinessTimeout

What: Env var (READINESS_TIMEOUT_MS) overriding readiness.timeout (milliseconds).

Why: Readiness sensitivity differs between local/dev and production.

How: Parsed by applyEnvOverrides() via parsePositiveDurationMillis.

envReadinessUserAgent

What: Env var (READINESS_USER_AGENT) overriding readiness.userAgent.

Why: Lets operators ensure readiness requests are identifiable in upstream logs.

How: Read by applyEnvOverrides() as a string.

envGitSHA

What: Env var (GIT_SHA) used to stamp build/version metadata.

Why: Build metadata is useful for debugging, rollouts, and health endpoints.

How: Read by Default() (and optionally overwritten by applyEnvOverrides()).

envJWTSecret

What: Env var (JWT_SECRET) holding the symmetric key used for JWT verification.

Why: Secrets should be injected at runtime via env/secret managers rather than embedded in YAML.

How: Read by applyEnvOverrides() into auth.secret; consumed by pkg/gateway/auth.

envJWTAudience

What: Env var (JWT_AUDIENCE) configuring acceptable JWT audiences.

Why: Audience sets often differ by environment and can evolve without code changes.

How: Parsed by applyEnvOverrides() using splitAndTrim into auth.audiences.

envJWTIssuer

What: Env var (JWT_ISSUER) configuring the expected JWT issuer.

Why: Separates auth policy from code and supports multi-environment deployments.

How: Read by applyEnvOverrides() into auth.issuer.

envCorsAllowedOrigins

What: Env var (CORS_ALLOWED_ORIGINS) overriding cors.allowedOrigins.

Why: CORS policy is commonly environment-specific and needs safe, deploy-time control.

How: Parsed by applyEnvOverrides() using splitAndTrim.

envRateLimitWindow

What: Env var (RATE_LIMIT_WINDOW_MS) overriding rateLimit.window (milliseconds).

Why: Allows deploy-time tuning of the rate-limit window without YAML edits.

How: Parsed by applyEnvOverrides() via parsePositiveDurationMillis.

envRateLimitMax

What: Env var (RATE_LIMIT_MAX) overriding rateLimit.max.

Why: Allows rate limiting to be tuned per environment without YAML edits.

How: Parsed by applyEnvOverrides() as an integer.

envMetricsEnabled

What: Env var (METRICS_ENABLED) controlling metrics exposure.

Why: Some environments may forbid metrics endpoints or want them disabled.

How: Parsed by applyEnvOverrides() as a boolean into metrics.enabled.

envAdminEnabled

What: Env var (ADMIN_ENABLED) toggling the admin server.

Why: Enables turning on/off the admin plane per environment at deploy time.

How: Parsed by applyEnvOverrides() as a boolean into admin.enabled.

envAdminListen

What: Env var (ADMIN_LISTEN) overriding admin.listen.

Why: Supports binding admin endpoints to a specific interface/port per environment.

How: Read by applyEnvOverrides(); defaulted by normalize() when missing.

envAdminToken

What: Env var (ADMIN_TOKEN) holding a bearer token for admin authentication.

Why: Encourages keeping admin auth secrets in secret managers, not YAML.

How: Read by applyEnvOverrides() into admin.token.

envAdminAllow

What: Env var (ADMIN_ALLOW) configuring an IP/CIDR allowlist for admin endpoints.

Why: Allows locking down admin access without editing YAML.

How: Parsed by applyEnvOverrides() using splitAndTrim and validated in Validate().

envTLSInsecureSkipVerify

What: Env var suffix (_TLS_INSECURE_SKIP_VERIFY) disabling upstream TLS verification for readiness checks.

Why: Useful for dev/test against self-signed certs; unsafe for production.

How: Parsed by applyUpstreamOverrides() and implicitly enables TLS when set.

Notes: Avoid in production; disables server certificate verification.

envTLSEnabled

What: Env var suffix (_TLS_ENABLED) toggling upstream TLS behavior.

Why: Allows enabling TLS through env configuration without editing YAML.

How: Parsed by applyUpstreamOverrides() as a boolean.

envTLSCAFile

What: Env var suffix (_TLS_CA_FILE) providing a PEM CA bundle path for upstream TLS verification.

Why: Supports internal PKI / custom root CAs via mounted secret files.

How: Read by applyUpstreamOverrides() and used by the runtime readiness TLS client configuration.

envTLSCertFile

What: Env var suffix (_TLS_CERT_FILE) providing a client certificate path for upstream mTLS.

Why: Supports upstreams that require client authentication.

How: Read by applyUpstreamOverrides(); validated together with _TLS_KEY_FILE.

envTLSKeyFile

What: Env var suffix (_TLS_KEY_FILE) providing a client private key path for upstream mTLS.

Why: Completes the mTLS key pair alongside _TLS_CERT_FILE.

How: Read by applyUpstreamOverrides(); validated together with _TLS_CERT_FILE.

envAPIURL

What: Env var suffix (_API_URL) appended to an upstream prefix to form the upstream base URL variable.

Why: Keeps env naming consistent across upstream products (e.g. TRADE_API_URL, TASK_API_URL).

How: Read by applyUpstreamOverrides() as prefix + envAPIURL.

envHealthPath

What: Env var suffix (_HEALTH_PATH) appended to an upstream prefix to form the upstream health path variable.

Why: Keeps env naming consistent across upstream products (e.g. TRADE_HEALTH_PATH, TASK_HEALTH_PATH).

How: Read by applyUpstreamOverrides() and canonicalized via ensureLeadingSlash.

Types

type block 1

pkg/gateway/config/config.go#L65
type Config struct {
Version string `yaml:"version"`
HTTP HTTPConfig `yaml:"http"`
Readiness ReadinessConfig `yaml:"readiness"`
Auth AuthConfig `yaml:"auth"`
CORS CORSConfig `yaml:"cors"`
RateLimit RateLimitConfig `yaml:"rateLimit"`
Metrics MetricsConfig `yaml:"metrics"`
Admin AdminConfig `yaml:"admin"`
WebSocket WebSocketConfig `yaml:"websocket"`
Webhooks WebhookConfig `yaml:"webhooks"`
}

Config

What: Root configuration object for the gateway runtime and SDK.

Why: Provides a stable schema for running the gateway via CLI and for embedding it as a library.

How: Created by Load() and then consumed by runtime/server packages to configure listeners, upstreams, auth, middleware, and feature flags.

type block 2

pkg/gateway/config/config.go#L79
type HTTPConfig struct {
Port int `yaml:"port"`
ShutdownTimeout Duration `yaml:"shutdownTimeout"`
}

HTTPConfig

What: Public HTTP server configuration (port and shutdown timeout).

Why: Keeps listener behavior explicit and environment-configurable.

How: Used by the server runtime to bind and to configure graceful shutdown.

type block 3

pkg/gateway/config/config.go#L85
type ReadinessConfig struct {
Timeout Duration `yaml:"timeout"`
UserAgent string `yaml:"userAgent"`
Upstreams []UpstreamConfig `yaml:"upstreams"`
}

ReadinessConfig

What: Readiness probing configuration (timeout, user-agent, upstream list).

Why: Readiness controls whether the gateway should receive traffic; it must reflect upstream reachability.

How: Used by the runtime to build the readiness checker; validated for required upstreams (trade/task).

type block 4

pkg/gateway/config/config.go#L92
type UpstreamConfig struct {
Name string `yaml:"name"`
BaseURL string `yaml:"baseURL"`
HealthPath string `yaml:"healthPath"`
TLS TLSConfig `yaml:"tls"`
}

UpstreamConfig

What: Upstream service configuration (name, base URL, health path, TLS options).

Why: The gateway proxies to multiple upstream products and needs per-upstream settings for probing and routing.

How: Loaded from defaults/YAML/env and used by readiness checks and proxy routing.

type block 5

pkg/gateway/config/config.go#L100
type TLSConfig struct {
Enabled bool `yaml:"enabled"`
InsecureSkipVerify bool `yaml:"insecureSkipVerify"`
CAFile string `yaml:"caFile"`
ClientCertFile string `yaml:"clientCertFile"`
ClientKeyFile string `yaml:"clientKeyFile"`
}

TLSConfig

What: Upstream TLS/mTLS configuration for readiness checks (enable, CA file, client cert/key, skip verify).

Why: Supports upstreams with internal PKI or client-auth requirements while keeping secrets/file paths out of code.

How: Applied to upstream configs and validated for cert/key pairing; used by runtime to build per-upstream TLS transports.

type block 6

pkg/gateway/config/config.go#L109
type AuthConfig struct {
Secret string `yaml:"secret"`
Audiences []string `yaml:"audiences"`
Issuer string `yaml:"issuer"`
}

AuthConfig

What: JWT verification configuration (secret, audiences, issuer).

Why: Keeps auth policy configurable across environments without changing code.

How: Used by pkg/gateway/auth when building the authenticator and auth middleware.

type block 7

pkg/gateway/config/config.go#L116
type CORSConfig struct {
AllowedOrigins []string `yaml:"allowedOrigins"`
}

CORSConfig

What: CORS configuration (allowed origins).

Why: Browser-facing clients require explicit CORS policy control.

How: Applied by server middleware when handling cross-origin requests.

type block 8

pkg/gateway/config/config.go#L121
type RateLimitConfig struct {
Window Duration `yaml:"window"`
Max int `yaml:"max"`
}

RateLimitConfig

What: Rate limiting configuration (window and max requests).

Why: Protects the gateway and upstreams from bursts and accidental abuse.

How: Consumed by rate limiting middleware; defaulted and validated by this package.

type block 9

pkg/gateway/config/config.go#L127
type MetricsConfig struct {
Enabled bool `yaml:"enabled"`
}

MetricsConfig

What: Metrics enablement configuration.

Why: Allows disabling metrics in constrained or special environments.

How: Read by runtime/server to decide whether to register/expose Prometheus metrics.

type block 10

pkg/gateway/config/config.go#L132
type WebSocketConfig struct {
MaxConcurrent int `yaml:"maxConcurrent"`
IdleTimeout Duration `yaml:"idleTimeout"`
}

WebSocketConfig

What: WebSocket connection policy (max concurrent and idle timeout).

Why: Upgraded connections are long-lived; limits protect against resource exhaustion and leaks.

How: Consumed by the server to reject upgrades at capacity and enforce idle timeouts.

type block 11

pkg/gateway/config/config.go#L138
type AdminConfig struct {
Enabled bool `yaml:"enabled"`
Listen string `yaml:"listen"`
Token string `yaml:"token"`
Allow []string `yaml:"allow"`
}

AdminConfig

What: Configuration for the admin/control-plane HTTP server (enable, listen, token, allowlist).

Why: Separates operational endpoints from the public gateway interface and supports tight access control.

How: Consumed by runtime/server when starting admin endpoints; validated when enabled.

type block 12

pkg/gateway/config/config.go#L146
type WebhookConfig struct {
Enabled bool `yaml:"enabled"`
Endpoints []WebhookEndpointConfig `yaml:"endpoints"`
}

WebhookConfig

What: Webhook ingestion configuration (enabled flag and endpoint list).

Why: Enables secure ingestion of event callbacks and controlled forwarding to upstream targets.

How: When enabled, server registers per-endpoint webhook handlers using the endpoint configs.

type block 13

pkg/gateway/config/config.go#L152
type WebhookEndpointConfig struct {
Name string `yaml:"name"`
Path string `yaml:"path"`
TargetURL string `yaml:"targetURL"`
Secret string `yaml:"secret"`
SignatureHeader string `yaml:"signatureHeader"`
MaxAttempts int `yaml:"maxAttempts"`
InitialBackoff Duration `yaml:"initialBackoff"`
Timeout Duration `yaml:"timeout"`
}

WebhookEndpointConfig

What: Per-endpoint webhook configuration (path, target URL, secret, signature header, retry/backoff, timeout).

Why: Different webhook senders may require different endpoints, secrets, and retry characteristics.

How: Normalized/validated here; used to construct pkg/gateway/webhook handlers and mount them in the server.

type block 14

pkg/gateway/config/config.go#L164
type Duration time.Duration

Duration

What: A YAML-friendly wrapper around time.Duration.

Why: Allows config fields to accept both 1s-style strings and millisecond integers.

How: Implements YAML marshal/unmarshal methods and exposes AsDuration() for consumers.

type block 15

pkg/gateway/config/config.go#L270
type Option func(*loaderOptions)

Option

What: Functional option type used to customize how Load() behaves.

Why: Keeps the Load() API stable while enabling targeted customization for CLI/tests.

How: Options mutate a private loaderOptions instance inside Load().

type block 16

pkg/gateway/config/config.go#L272
type loaderOptions struct {
paths []string
lookupEnv func(string) (string, bool)
}

loaderOptions

What: Internal accumulator for config-loading options (YAML paths and env lookup function).

Why: Keeps Load() testable and configurable without global state.

How: Mutated by WithPath and WithLookupEnv, then consumed by Load().

Functions and Methods

(Duration).AsDuration

What: Converts the wrapper to a time.Duration.

Why: Makes transitions between config types and standard library types explicit.

How: Implemented as a simple type conversion.

pkg/gateway/config/config.go#L167
func (d Duration) AsDuration() time.Duration {
return time.Duration(d)
}

Walkthrough

The list below documents the statements inside the function body, including nested blocks and inline closures.

  • L168: return time.Duration(d)
    • What: Returns from the current function.
    • Why: Ends the current execution path and hands control back to the caller.
    • How: Executes a return statement (possibly returning values).

(Duration).MarshalYAML

What: Encodes a Duration as a Go duration string for YAML output.

Why: Produces human-readable YAML when configs are emitted/converted.

How: Returns d.AsDuration().String() to the YAML encoder.

pkg/gateway/config/config.go#L172
func (d Duration) MarshalYAML() (interface{}, error) {
return d.AsDuration().String(), nil
}

Walkthrough

The list below documents the statements inside the function body, including nested blocks and inline closures.

  • L173: return d.AsDuration().String(), nil
    • What: Returns from the current function.
    • Why: Ends the current execution path and hands control back to the caller.
    • How: Executes a return statement (possibly returning values).

(*Duration).UnmarshalYAML

What: Parses a YAML scalar into a Duration.

Why: Supports both Go duration strings (1s) and numeric millisecond strings (2000) in config.

How: Treats integer-looking scalars as milliseconds; otherwise uses time.ParseDuration. Rejects negative values.

pkg/gateway/config/config.go#L177
func (d *Duration) UnmarshalYAML(value *yaml.Node) error {
if value == nil {
return nil
}

switch value.Kind {
case yaml.ScalarNode:
txt := strings.TrimSpace(value.Value)
if txt == "" {
*d = Duration(0)
return nil
}
if ms, err := strconv.Atoi(txt); err == nil {
if ms < 0 {
return fmt.Errorf("duration must be non-negative, got %d", ms)
}
*d = Duration(time.Duration(ms) * time.Millisecond)
return nil
}
parsed, err := time.ParseDuration(txt)
if err != nil {
return fmt.Errorf("parse duration %q: %w", txt, err)
}
if parsed < 0 {
return fmt.Errorf("duration must be non-negative, got %s", parsed)
}
*d = Duration(parsed)
return nil
default:
return fmt.Errorf("unsupported duration node kind: %v", value.Kind)
}
}

Walkthrough

The list below documents the statements inside the function body, including nested blocks and inline closures.

  • L178: if value == nil { return nil }
    • What: Branches conditionally.
    • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L179: return nil
        • What: Returns from the current function.
        • Why: Ends the current execution path and hands control back to the caller.
        • How: Executes a return statement (possibly returning values).
  • L182: switch value.Kind { case yaml.ScalarNode: txt := strings.TrimSpace(value.Value) if txt == "" { *d = Duration(0) return nil } if ms, err := …
    • What: Selects a branch from multiple cases.
    • Why: Keeps multi-case branching readable and explicit.
    • How: Evaluates the switch expression and executes the first matching case.
    • Nested steps:
      • L183: case yaml.ScalarNode:
        • What: Selects a switch case.
        • Why: Makes multi-branch control flow explicit and readable.
        • How: Runs this case body when the switch value matches (or when default is selected).
        • Nested steps:
          • L184: txt := strings.TrimSpace(value.Value)
            • What: Defines txt.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
          • L185: if txt == "" { *d = Duration(0) return nil }
            • What: Branches conditionally.
            • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
            • How: Evaluates the condition and executes the matching branch.
            • Nested steps:
              • L186: *d = Duration(0)
                • What: Assigns *d.
                • Why: Keeps intermediate state available for later steps in the function.
                • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
              • L187: return nil
                • What: Returns from the current function.
                • Why: Ends the current execution path and hands control back to the caller.
                • How: Executes a return statement (possibly returning values).
          • L189: if ms, err := strconv.Atoi(txt); err == nil { if ms < 0 { return fmt.Errorf("duration must be non-negative, got %d", ms) } *d = Duration(ti…
            • What: Branches conditionally.
            • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
            • How: Evaluates the condition and executes the matching branch.
            • Nested steps:
              • L189: ms, err := strconv.Atoi(txt)
                • What: Defines ms, err.
                • Why: Keeps intermediate state available for later steps in the function.
                • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
              • L190: if ms < 0 { return fmt.Errorf("duration must be non-negative, got %d", ms) }
                • What: Branches conditionally.
                • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
                • How: Evaluates the condition and executes the matching branch.
                • Nested steps:
                  • L191: return fmt.Errorf("duration must be non-negative, got %d", ms)
                    • What: Returns from the current function.
                    • Why: Ends the current execution path and hands control back to the caller.
                    • How: Executes a return statement (possibly returning values).
              • L193: *d = Duration(time.Duration(ms) * time.Millisecond)
                • What: Assigns *d.
                • Why: Keeps intermediate state available for later steps in the function.
                • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
              • L194: return nil
                • What: Returns from the current function.
                • Why: Ends the current execution path and hands control back to the caller.
                • How: Executes a return statement (possibly returning values).
          • L196: parsed, err := time.ParseDuration(txt)
            • What: Defines parsed, err.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
          • L197: if err != nil { return fmt.Errorf("parse duration %q: %w", txt, err) }
            • What: Branches conditionally.
            • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
            • How: Evaluates the condition and executes the matching branch.
            • Nested steps:
              • L198: return fmt.Errorf("parse duration %q: %w", txt, err)
                • What: Returns from the current function.
                • Why: Ends the current execution path and hands control back to the caller.
                • How: Executes a return statement (possibly returning values).
          • L200: if parsed < 0 { return fmt.Errorf("duration must be non-negative, got %s", parsed) }
            • What: Branches conditionally.
            • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
            • How: Evaluates the condition and executes the matching branch.
            • Nested steps:
              • L201: return fmt.Errorf("duration must be non-negative, got %s", parsed)
                • What: Returns from the current function.
                • Why: Ends the current execution path and hands control back to the caller.
                • How: Executes a return statement (possibly returning values).
          • L203: *d = Duration(parsed)
            • What: Assigns *d.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
          • L204: return nil
            • What: Returns from the current function.
            • Why: Ends the current execution path and hands control back to the caller.
            • How: Executes a return statement (possibly returning values).
      • L205: default:
        • What: Selects a switch case.
        • Why: Makes multi-branch control flow explicit and readable.
        • How: Runs this case body when the switch value matches (or when default is selected).
        • Nested steps:
          • L206: return fmt.Errorf("unsupported duration node kind: %v", value.Kind)
            • What: Returns from the current function.
            • Why: Ends the current execution path and hands control back to the caller.
            • How: Executes a return statement (possibly returning values).

DurationFrom

What: Converts time.Duration into the config Duration wrapper type.

Why: Keeps default-setting code readable and consistent.

How: Used by Default() and normalize() when assigning durations.

pkg/gateway/config/config.go#L211
func DurationFrom(d time.Duration) Duration {
return Duration(d)
}

Walkthrough

The list below documents the statements inside the function body, including nested blocks and inline closures.

  • L212: return Duration(d)
    • What: Returns from the current function.
    • Why: Ends the current execution path and hands control back to the caller.
    • How: Executes a return statement (possibly returning values).

Default

What: Constructs a baseline Config with safe defaults.

Why: Provides predictable behavior when YAML/env inputs are partial and gives Load() a stable base layer.

How: Initializes default timeouts/ports/limits, creates trade/task upstream stubs, and sets Config.Version from GIT_SHA.

pkg/gateway/config/config.go#L216
func Default() Config {
return Config{
Version: os.Getenv(envGitSHA),
HTTP: HTTPConfig{
Port: defaultPort,
ShutdownTimeout: DurationFrom(defaultShutdownTimeout),
},
Readiness: ReadinessConfig{
Timeout: DurationFrom(defaultReadinessTimeout),
UserAgent: defaultReadinessUserAgent,
Upstreams: []UpstreamConfig{
{
Name: "trade",
BaseURL: "",
HealthPath: defaultHealthPath,
TLS: TLSConfig{},
},
{
Name: "task",
BaseURL: "",
HealthPath: defaultHealthPath,
TLS: TLSConfig{},
},
},
},
Auth: AuthConfig{},
CORS: CORSConfig{
AllowedOrigins: nil,
},
RateLimit: RateLimitConfig{
Window: DurationFrom(defaultRateLimitWindow),
Max: defaultRateLimitMax,
},
Metrics: MetricsConfig{
Enabled: defaultMetricsEnabled,
},
Admin: AdminConfig{
Enabled: false,
Listen: defaultAdminListen,
Token: "",
Allow: nil,
},
WebSocket: WebSocketConfig{
MaxConcurrent: defaultWebSocketMaxConcurrent,
IdleTimeout: DurationFrom(defaultWebSocketIdleTimeout),
},
Webhooks: WebhookConfig{
Enabled: false,
Endpoints: nil,
},
}
}

Walkthrough

The list below documents the statements inside the function body, including nested blocks and inline closures.

  • L217: return Config{ Version: os.Getenv(envGitSHA), HTTP: HTTPConfig{ Port: defaultPort, ShutdownTimeout: DurationFrom(defaultShutdownTimeout), }…
    • What: Returns from the current function.
    • Why: Ends the current execution path and hands control back to the caller.
    • How: Executes a return statement (possibly returning values).

WithPath

What: Option that adds a YAML config path to attempt loading.

Why: Lets CLI/tests specify config file(s) without relying on global state.

How: Appends to loaderOptions.paths when the provided path is non-empty.

pkg/gateway/config/config.go#L278
func WithPath(path string) Option {
return func(o *loaderOptions) {
if strings.TrimSpace(path) != "" {
o.paths = append(o.paths, path)
}
}
}

Walkthrough

The list below documents the statements inside the function body, including nested blocks and inline closures.

  • L279: return func(o *loaderOptions) { if strings.TrimSpace(path) != "" { o.paths = append(o.paths, path) } }
    • What: Returns from the current function.
    • Why: Ends the current execution path and hands control back to the caller.
    • How: Executes a return statement (possibly returning values).
    • Nested steps:
      • L279: func(o *loaderOptions) { if strings.TrimSpace(path) != "" { o.paths = append(o.paths, path) } }
        • What: Defines an inline function (closure).
        • Why: Encapsulates callback logic and may capture variables from the surrounding scope.
        • How: Declares a func literal and uses it as a value (for example, as an HTTP handler or callback).
        • Nested steps:
          • L280: if strings.TrimSpace(path) != "" { o.paths = append(o.paths, path) }
            • What: Branches conditionally.
            • Why: Handles different execution paths based on runtime state.
            • How: Evaluates the condition and executes the matching branch.
            • Nested steps:
              • L281: o.paths = append(o.paths, path)
                • What: Assigns o.paths.
                • Why: Keeps intermediate state available for later steps in the function.
                • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.

WithLookupEnv

What: Option that overrides how environment variables are looked up.

Why: Enables deterministic tests without mutating real process environment.

How: Sets loaderOptions.lookupEnv, which is passed into applyEnvOverrides.

pkg/gateway/config/config.go#L287
func WithLookupEnv(fn func(string) (string, bool)) Option {
return func(o *loaderOptions) {
o.lookupEnv = fn
}
}

Walkthrough

The list below documents the statements inside the function body, including nested blocks and inline closures.

  • L288: return func(o *loaderOptions) { o.lookupEnv = fn }
    • What: Returns from the current function.
    • Why: Ends the current execution path and hands control back to the caller.
    • How: Executes a return statement (possibly returning values).
    • Nested steps:
      • L288: func(o *loaderOptions) { o.lookupEnv = fn }
        • What: Defines an inline function (closure).
        • Why: Encapsulates callback logic and may capture variables from the surrounding scope.
        • How: Declares a func literal and uses it as a value (for example, as an HTTP handler or callback).
        • Nested steps:
          • L289: o.lookupEnv = fn
            • What: Assigns o.lookupEnv.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.

Load

What: Loads configuration by merging defaults, YAML file(s), and environment overrides.

Why: Supports both config-file-driven deployments and env-driven deployments (especially for secrets).

How:

  • Builds loaderOptions (paths + env lookup)
  • Seeds paths from APIGW_CONFIG
  • Applies any Options (e.g. WithPath)
  • Starts from Default()
  • Reads and unmarshals YAML (skipping missing files)
  • Applies env overrides (applyEnvOverrides)
  • Normalizes (normalize) and validates (Validate)

Notes: Order matters: later layers override earlier layers.

pkg/gateway/config/config.go#L294
func Load(opts ...Option) (Config, error) {
options := loaderOptions{
lookupEnv: os.LookupEnv,
}
if envPath := strings.TrimSpace(os.Getenv(defaultConfigEnvVar)); envPath != "" {
options.paths = append(options.paths, envPath)
}
for _, opt := range opts {
if opt != nil {
opt(&options)
}
}

cfg := Default()

for _, path := range options.paths {
if strings.TrimSpace(path) == "" {
continue
}
data, err := os.ReadFile(path)
switch {
case errors.Is(err, os.ErrNotExist):
continue
case err != nil:
return cfg, fmt.Errorf("read config %q: %w", path, err)
}
if err := yaml.Unmarshal(data, &cfg); err != nil {
return cfg, fmt.Errorf("decode config %q: %w", path, err)
}
}

if err := applyEnvOverrides(&cfg, options.lookupEnv); err != nil {
return cfg, err
}

if err := cfg.normalize(); err != nil {
return cfg, err
}

if err := cfg.Validate(); err != nil {
return cfg, err
}

return cfg, nil
}

Walkthrough

Expand walkthrough (30 steps)

The list below documents the statements inside the function body, including nested blocks and inline closures.

  • L295: options := loaderOptions{ lookupEnv: os.LookupEnv, }
    • What: Defines options.
    • Why: Keeps intermediate state available for later steps in the function.
    • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L298: if envPath := strings.TrimSpace(os.Getenv(defaultConfigEnvVar)); envPath != "" { options.paths = append(options.paths, envPath) }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L298: envPath := strings.TrimSpace(os.Getenv(defaultConfigEnvVar))
        • What: Defines envPath.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L299: options.paths = append(options.paths, envPath)
        • What: Assigns options.paths.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L301: for _, opt := range opts { if opt != nil { opt(&options) } }
    • What: Iterates over a collection.
    • Why: Processes multiple elements with the same logic.
    • How: Executes a for ... range loop.
    • Nested steps:
      • L302: if opt != nil { opt(&options) }
        • What: Branches conditionally.
        • Why: Handles different execution paths based on runtime state.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L303: opt(&options)
            • What: Calls opt.
            • Why: Performs side effects or delegates work to a helper.
            • How: Executes the expression statement.
  • L307: cfg := Default()
    • What: Defines cfg.
    • Why: Keeps intermediate state available for later steps in the function.
    • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L309: for _, path := range options.paths { if strings.TrimSpace(path) == "" { continue } data, err := os.ReadFile(path) switch { case errors.Is(e…
    • What: Iterates over a collection.
    • Why: Processes multiple elements with the same logic.
    • How: Executes a for ... range loop.
    • Nested steps:
      • L310: if strings.TrimSpace(path) == "" { continue }
        • What: Branches conditionally.
        • Why: Handles different execution paths based on runtime state.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L311: continue
            • What: Executes a statement.
            • Why: Advances the function logic.
            • How: Runs this statement as part of the function body.
      • L313: data, err := os.ReadFile(path)
        • What: Defines data, err.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L314: switch { case errors.Is(err, os.ErrNotExist): continue case err != nil: return cfg, fmt.Errorf("read config %q: %w", path, err) }
        • What: Selects a branch from multiple cases.
        • Why: Keeps multi-case branching readable and explicit.
        • How: Evaluates the switch expression and executes the first matching case.
        • Nested steps:
          • L315: case errors.Is(err, os.ErrNotExist):
            • What: Selects a switch case.
            • Why: Makes multi-branch control flow explicit and readable.
            • How: Runs this case body when the switch value matches (or when default is selected).
            • Nested steps:
              • L316: continue
                • What: Executes a statement.
                • Why: Advances the function logic.
                • How: Runs this statement as part of the function body.
          • L317: case err != nil:
            • What: Selects a switch case.
            • Why: Makes multi-branch control flow explicit and readable.
            • How: Runs this case body when the switch value matches (or when default is selected).
            • Nested steps:
              • L318: return cfg, fmt.Errorf("read config %q: %w", path, err)
                • What: Returns from the current function.
                • Why: Ends the current execution path and hands control back to the caller.
                • How: Executes a return statement (possibly returning values).
      • L320: if err := yaml.Unmarshal(data, &cfg); err != nil { return cfg, fmt.Errorf("decode config %q: %w", path, err) }
        • What: Branches conditionally.
        • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L320: err := yaml.Unmarshal(data, &cfg)
            • What: Defines err.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
          • L321: return cfg, fmt.Errorf("decode config %q: %w", path, err)
            • What: Returns from the current function.
            • Why: Ends the current execution path and hands control back to the caller.
            • How: Executes a return statement (possibly returning values).
  • L325: if err := applyEnvOverrides(&cfg, options.lookupEnv); err != nil { return cfg, err }
    • What: Branches conditionally.
    • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L325: err := applyEnvOverrides(&cfg, options.lookupEnv)
        • What: Defines err.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L326: return cfg, err
        • What: Returns from the current function.
        • Why: Ends the current execution path and hands control back to the caller.
        • How: Executes a return statement (possibly returning values).
  • L329: if err := cfg.normalize(); err != nil { return cfg, err }
    • What: Branches conditionally.
    • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L329: err := cfg.normalize()
        • What: Defines err.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L330: return cfg, err
        • What: Returns from the current function.
        • Why: Ends the current execution path and hands control back to the caller.
        • How: Executes a return statement (possibly returning values).
  • L333: if err := cfg.Validate(); err != nil { return cfg, err }
    • What: Branches conditionally.
    • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L333: err := cfg.Validate()
        • What: Defines err.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L334: return cfg, err
        • What: Returns from the current function.
        • Why: Ends the current execution path and hands control back to the caller.
        • How: Executes a return statement (possibly returning values).
  • L337: return cfg, nil
    • What: Returns from the current function.
    • Why: Ends the current execution path and hands control back to the caller.
    • How: Executes a return statement (possibly returning values).

applyEnvOverrides

What: Applies environment-variable overrides to an existing Config.

Why: Deployments frequently inject secrets and runtime knobs via env vars; this layer keeps overrides explicit and validated.

How:

  • Reads known gateway-level env vars (port, timeouts, auth, CORS, rate limiting, metrics, admin)
  • Calls applyUpstreamOverrides for the trade/task upstream prefixes
  • Leaves YAML/default values untouched when env vars are absent
pkg/gateway/config/config.go#L340
func applyEnvOverrides(cfg *Config, lookup func(string) (string, bool)) error {
if lookup == nil {
lookup = os.LookupEnv
}

if val, ok := lookup(envPort); ok && strings.TrimSpace(val) != "" {
port, err := strconv.Atoi(strings.TrimSpace(val))
if err != nil || port <= 0 {
return fmt.Errorf("invalid %s value: %s", envPort, val)
}
cfg.HTTP.Port = port
}

if val, ok := lookup(envShutdownTimeout); ok && strings.TrimSpace(val) != "" {
timeout, err := parsePositiveDurationMillis(val)
if err != nil {
return fmt.Errorf("invalid %s: %w", envShutdownTimeout, err)
}
cfg.HTTP.ShutdownTimeout = DurationFrom(timeout)
}

if val, ok := lookup(envReadinessTimeout); ok && strings.TrimSpace(val) != "" {
timeout, err := parsePositiveDurationMillis(val)
if err != nil {
return fmt.Errorf("invalid %s: %w", envReadinessTimeout, err)
}
cfg.Readiness.Timeout = DurationFrom(timeout)
}

if val, ok := lookup(envReadinessUserAgent); ok && strings.TrimSpace(val) != "" {
cfg.Readiness.UserAgent = strings.TrimSpace(val)
}

if val, ok := lookup(envGitSHA); ok && strings.TrimSpace(val) != "" {
cfg.Version = strings.TrimSpace(val)
}

if val, ok := lookup(envJWTSecret); ok && strings.TrimSpace(val) != "" {
cfg.Auth.Secret = strings.TrimSpace(val)
}

if val, ok := lookup(envJWTAudience); ok && strings.TrimSpace(val) != "" {
cfg.Auth.Audiences = splitAndTrim(val)
}

if val, ok := lookup(envJWTIssuer); ok && strings.TrimSpace(val) != "" {
cfg.Auth.Issuer = strings.TrimSpace(val)
}

if val, ok := lookup(envCorsAllowedOrigins); ok && strings.TrimSpace(val) != "" {
cfg.CORS.AllowedOrigins = splitAndTrim(val)
}

if val, ok := lookup(envRateLimitWindow); ok && strings.TrimSpace(val) != "" {
window, err := parsePositiveDurationMillis(val)
if err != nil {
return fmt.Errorf("invalid %s: %w", envRateLimitWindow, err)
}
cfg.RateLimit.Window = DurationFrom(window)
}

if val, ok := lookup(envRateLimitMax); ok && strings.TrimSpace(val) != "" {
max, err := strconv.Atoi(strings.TrimSpace(val))
if err != nil || max <= 0 {
return fmt.Errorf("invalid %s: %s", envRateLimitMax, val)
}
cfg.RateLimit.Max = max
}

if val, ok := lookup(envMetricsEnabled); ok && strings.TrimSpace(val) != "" {
enabled, err := strconv.ParseBool(strings.TrimSpace(val))
if err != nil {
return fmt.Errorf("invalid %s: %w", envMetricsEnabled, err)
}
cfg.Metrics.Enabled = enabled
}

if err := applyUpstreamOverrides(cfg, lookup, envTradePrefix); err != nil {
return fmt.Errorf("trade upstream config: %w", err)
}
if err := applyUpstreamOverrides(cfg, lookup, envTaskPrefix); err != nil {
return fmt.Errorf("task upstream config: %w", err)
}

if val, ok := lookup(envAdminEnabled); ok && strings.TrimSpace(val) != "" {
enabled, err := strconv.ParseBool(strings.TrimSpace(val))
if err != nil {
return fmt.Errorf("invalid %s: %w", envAdminEnabled, err)
}
cfg.Admin.Enabled = enabled
}

if val, ok := lookup(envAdminListen); ok && strings.TrimSpace(val) != "" {
cfg.Admin.Listen = strings.TrimSpace(val)
}

if val, ok := lookup(envAdminToken); ok {
cfg.Admin.Token = strings.TrimSpace(val)
}

if val, ok := lookup(envAdminAllow); ok && strings.TrimSpace(val) != "" {
cfg.Admin.Allow = splitAndTrim(val)
}

return nil
}

Walkthrough

Expand walkthrough (78 steps)

The list below documents the statements inside the function body, including nested blocks and inline closures.

  • L341: if lookup == nil { lookup = os.LookupEnv }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L342: lookup = os.LookupEnv
        • What: Assigns lookup.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L345: if val, ok := lookup(envPort); ok && strings.TrimSpace(val) != "" { port, err := strconv.Atoi(strings.TrimSpace(val)) if err != nil || port…
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L345: val, ok := lookup(envPort)
        • What: Defines val, ok.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L346: port, err := strconv.Atoi(strings.TrimSpace(val))
        • What: Defines port, err.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L347: if err != nil || port <= 0 { return fmt.Errorf("invalid %s value: %s", envPort, val) }
        • What: Branches conditionally.
        • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L348: return fmt.Errorf("invalid %s value: %s", envPort, val)
            • What: Returns from the current function.
            • Why: Ends the current execution path and hands control back to the caller.
            • How: Executes a return statement (possibly returning values).
      • L350: cfg.HTTP.Port = port
        • What: Assigns cfg.HTTP.Port.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L353: if val, ok := lookup(envShutdownTimeout); ok && strings.TrimSpace(val) != "" { timeout, err := parsePositiveDurationMillis(val) if err != n…
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L353: val, ok := lookup(envShutdownTimeout)
        • What: Defines val, ok.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L354: timeout, err := parsePositiveDurationMillis(val)
        • What: Defines timeout, err.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L355: if err != nil { return fmt.Errorf("invalid %s: %w", envShutdownTimeout, err) }
        • What: Branches conditionally.
        • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L356: return fmt.Errorf("invalid %s: %w", envShutdownTimeout, err)
            • What: Returns from the current function.
            • Why: Ends the current execution path and hands control back to the caller.
            • How: Executes a return statement (possibly returning values).
      • L358: cfg.HTTP.ShutdownTimeout = DurationFrom(timeout)
        • What: Assigns cfg.HTTP.ShutdownTimeout.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L361: if val, ok := lookup(envReadinessTimeout); ok && strings.TrimSpace(val) != "" { timeout, err := parsePositiveDurationMillis(val) if err != …
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L361: val, ok := lookup(envReadinessTimeout)
        • What: Defines val, ok.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L362: timeout, err := parsePositiveDurationMillis(val)
        • What: Defines timeout, err.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L363: if err != nil { return fmt.Errorf("invalid %s: %w", envReadinessTimeout, err) }
        • What: Branches conditionally.
        • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L364: return fmt.Errorf("invalid %s: %w", envReadinessTimeout, err)
            • What: Returns from the current function.
            • Why: Ends the current execution path and hands control back to the caller.
            • How: Executes a return statement (possibly returning values).
      • L366: cfg.Readiness.Timeout = DurationFrom(timeout)
        • What: Assigns cfg.Readiness.Timeout.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L369: if val, ok := lookup(envReadinessUserAgent); ok && strings.TrimSpace(val) != "" { cfg.Readiness.UserAgent = strings.TrimSpace(val) }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L369: val, ok := lookup(envReadinessUserAgent)
        • What: Defines val, ok.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L370: cfg.Readiness.UserAgent = strings.TrimSpace(val)
        • What: Assigns cfg.Readiness.UserAgent.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L373: if val, ok := lookup(envGitSHA); ok && strings.TrimSpace(val) != "" { cfg.Version = strings.TrimSpace(val) }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L373: val, ok := lookup(envGitSHA)
        • What: Defines val, ok.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L374: cfg.Version = strings.TrimSpace(val)
        • What: Assigns cfg.Version.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L377: if val, ok := lookup(envJWTSecret); ok && strings.TrimSpace(val) != "" { cfg.Auth.Secret = strings.TrimSpace(val) }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L377: val, ok := lookup(envJWTSecret)
        • What: Defines val, ok.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L378: cfg.Auth.Secret = strings.TrimSpace(val)
        • What: Assigns cfg.Auth.Secret.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L381: if val, ok := lookup(envJWTAudience); ok && strings.TrimSpace(val) != "" { cfg.Auth.Audiences = splitAndTrim(val) }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L381: val, ok := lookup(envJWTAudience)
        • What: Defines val, ok.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L382: cfg.Auth.Audiences = splitAndTrim(val)
        • What: Assigns cfg.Auth.Audiences.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L385: if val, ok := lookup(envJWTIssuer); ok && strings.TrimSpace(val) != "" { cfg.Auth.Issuer = strings.TrimSpace(val) }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L385: val, ok := lookup(envJWTIssuer)
        • What: Defines val, ok.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L386: cfg.Auth.Issuer = strings.TrimSpace(val)
        • What: Assigns cfg.Auth.Issuer.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L389: if val, ok := lookup(envCorsAllowedOrigins); ok && strings.TrimSpace(val) != "" { cfg.CORS.AllowedOrigins = splitAndTrim(val) }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L389: val, ok := lookup(envCorsAllowedOrigins)
        • What: Defines val, ok.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L390: cfg.CORS.AllowedOrigins = splitAndTrim(val)
        • What: Assigns cfg.CORS.AllowedOrigins.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L393: if val, ok := lookup(envRateLimitWindow); ok && strings.TrimSpace(val) != "" { window, err := parsePositiveDurationMillis(val) if err != ni…
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L393: val, ok := lookup(envRateLimitWindow)
        • What: Defines val, ok.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L394: window, err := parsePositiveDurationMillis(val)
        • What: Defines window, err.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L395: if err != nil { return fmt.Errorf("invalid %s: %w", envRateLimitWindow, err) }
        • What: Branches conditionally.
        • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L396: return fmt.Errorf("invalid %s: %w", envRateLimitWindow, err)
            • What: Returns from the current function.
            • Why: Ends the current execution path and hands control back to the caller.
            • How: Executes a return statement (possibly returning values).
      • L398: cfg.RateLimit.Window = DurationFrom(window)
        • What: Assigns cfg.RateLimit.Window.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L401: if val, ok := lookup(envRateLimitMax); ok && strings.TrimSpace(val) != "" { max, err := strconv.Atoi(strings.TrimSpace(val)) if err != nil …
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L401: val, ok := lookup(envRateLimitMax)
        • What: Defines val, ok.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L402: max, err := strconv.Atoi(strings.TrimSpace(val))
        • What: Defines max, err.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L403: if err != nil || max <= 0 { return fmt.Errorf("invalid %s: %s", envRateLimitMax, val) }
        • What: Branches conditionally.
        • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L404: return fmt.Errorf("invalid %s: %s", envRateLimitMax, val)
            • What: Returns from the current function.
            • Why: Ends the current execution path and hands control back to the caller.
            • How: Executes a return statement (possibly returning values).
      • L406: cfg.RateLimit.Max = max
        • What: Assigns cfg.RateLimit.Max.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L409: if val, ok := lookup(envMetricsEnabled); ok && strings.TrimSpace(val) != "" { enabled, err := strconv.ParseBool(strings.TrimSpace(val)) if …
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L409: val, ok := lookup(envMetricsEnabled)
        • What: Defines val, ok.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L410: enabled, err := strconv.ParseBool(strings.TrimSpace(val))
        • What: Defines enabled, err.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L411: if err != nil { return fmt.Errorf("invalid %s: %w", envMetricsEnabled, err) }
        • What: Branches conditionally.
        • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L412: return fmt.Errorf("invalid %s: %w", envMetricsEnabled, err)
            • What: Returns from the current function.
            • Why: Ends the current execution path and hands control back to the caller.
            • How: Executes a return statement (possibly returning values).
      • L414: cfg.Metrics.Enabled = enabled
        • What: Assigns cfg.Metrics.Enabled.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L417: if err := applyUpstreamOverrides(cfg, lookup, envTradePrefix); err != nil { return fmt.Errorf("trade upstream config: %w", err) }
    • What: Branches conditionally.
    • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L417: err := applyUpstreamOverrides(cfg, lookup, envTradePrefix)
        • What: Defines err.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L418: return fmt.Errorf("trade upstream config: %w", err)
        • What: Returns from the current function.
        • Why: Ends the current execution path and hands control back to the caller.
        • How: Executes a return statement (possibly returning values).
  • L420: if err := applyUpstreamOverrides(cfg, lookup, envTaskPrefix); err != nil { return fmt.Errorf("task upstream config: %w", err) }
    • What: Branches conditionally.
    • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L420: err := applyUpstreamOverrides(cfg, lookup, envTaskPrefix)
        • What: Defines err.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L421: return fmt.Errorf("task upstream config: %w", err)
        • What: Returns from the current function.
        • Why: Ends the current execution path and hands control back to the caller.
        • How: Executes a return statement (possibly returning values).
  • L424: if val, ok := lookup(envAdminEnabled); ok && strings.TrimSpace(val) != "" { enabled, err := strconv.ParseBool(strings.TrimSpace(val)) if er…
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L424: val, ok := lookup(envAdminEnabled)
        • What: Defines val, ok.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L425: enabled, err := strconv.ParseBool(strings.TrimSpace(val))
        • What: Defines enabled, err.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L426: if err != nil { return fmt.Errorf("invalid %s: %w", envAdminEnabled, err) }
        • What: Branches conditionally.
        • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L427: return fmt.Errorf("invalid %s: %w", envAdminEnabled, err)
            • What: Returns from the current function.
            • Why: Ends the current execution path and hands control back to the caller.
            • How: Executes a return statement (possibly returning values).
      • L429: cfg.Admin.Enabled = enabled
        • What: Assigns cfg.Admin.Enabled.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L432: if val, ok := lookup(envAdminListen); ok && strings.TrimSpace(val) != "" { cfg.Admin.Listen = strings.TrimSpace(val) }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L432: val, ok := lookup(envAdminListen)
        • What: Defines val, ok.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L433: cfg.Admin.Listen = strings.TrimSpace(val)
        • What: Assigns cfg.Admin.Listen.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L436: if val, ok := lookup(envAdminToken); ok { cfg.Admin.Token = strings.TrimSpace(val) }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L436: val, ok := lookup(envAdminToken)
        • What: Defines val, ok.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L437: cfg.Admin.Token = strings.TrimSpace(val)
        • What: Assigns cfg.Admin.Token.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L440: if val, ok := lookup(envAdminAllow); ok && strings.TrimSpace(val) != "" { cfg.Admin.Allow = splitAndTrim(val) }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L440: val, ok := lookup(envAdminAllow)
        • What: Defines val, ok.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L441: cfg.Admin.Allow = splitAndTrim(val)
        • What: Assigns cfg.Admin.Allow.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L444: return nil
    • What: Returns from the current function.
    • Why: Ends the current execution path and hands control back to the caller.
    • How: Executes a return statement (possibly returning values).

applyUpstreamOverrides

What: Applies per-upstream env overrides for a given upstream prefix (e.g. TRADE, TASK).

Why: Centralizes upstream override logic and keeps naming consistent across products.

How: Ensures the upstream exists (via ensureUpstream), then applies base URL, health path, and TLS-related env vars.

pkg/gateway/config/config.go#L447
func applyUpstreamOverrides(cfg *Config, lookup func(string) (string, bool), prefix string) error {
upstream := cfg.ensureUpstream(prefix)

if val, ok := lookup(prefix + envAPIURL); ok && strings.TrimSpace(val) != "" {
upstream.BaseURL = strings.TrimSpace(val)
}
if val, ok := lookup(prefix + envHealthPath); ok && strings.TrimSpace(val) != "" {
upstream.HealthPath = ensureLeadingSlash(strings.TrimSpace(val))
}

if val, ok := lookup(prefix + envTLSEnabled); ok && strings.TrimSpace(val) != "" {
enabled, err := strconv.ParseBool(strings.TrimSpace(val))
if err != nil {
return fmt.Errorf("invalid %s%s: %w", prefix, envTLSEnabled, err)
}
upstream.TLS.Enabled = enabled
}

if val, ok := lookup(prefix + envTLSInsecureSkipVerify); ok && strings.TrimSpace(val) != "" {
enabled, err := strconv.ParseBool(strings.TrimSpace(val))
if err != nil {
return fmt.Errorf("invalid %s%s: %w", prefix, envTLSInsecureSkipVerify, err)
}
upstream.TLS.InsecureSkipVerify = enabled
if enabled {
upstream.TLS.Enabled = true
}
}

if val, ok := lookup(prefix + envTLSCAFile); ok && strings.TrimSpace(val) != "" {
upstream.TLS.CAFile = strings.TrimSpace(val)
upstream.TLS.Enabled = true
}
if val, ok := lookup(prefix + envTLSCertFile); ok && strings.TrimSpace(val) != "" {
upstream.TLS.ClientCertFile = strings.TrimSpace(val)
upstream.TLS.Enabled = true
}
if val, ok := lookup(prefix + envTLSKeyFile); ok && strings.TrimSpace(val) != "" {
upstream.TLS.ClientKeyFile = strings.TrimSpace(val)
upstream.TLS.Enabled = true
}

return nil
}

Walkthrough

Expand walkthrough (34 steps)

The list below documents the statements inside the function body, including nested blocks and inline closures.

  • L448: upstream := cfg.ensureUpstream(prefix)
    • What: Defines upstream.
    • Why: Keeps intermediate state available for later steps in the function.
    • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L450: if val, ok := lookup(prefix + envAPIURL); ok && strings.TrimSpace(val) != "" { upstream.BaseURL = strings.TrimSpace(val) }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L450: val, ok := lookup(prefix + envAPIURL)
        • What: Defines val, ok.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L451: upstream.BaseURL = strings.TrimSpace(val)
        • What: Assigns upstream.BaseURL.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L453: if val, ok := lookup(prefix + envHealthPath); ok && strings.TrimSpace(val) != "" { upstream.HealthPath = ensureLeadingSlash(strings.TrimSpa…
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L453: val, ok := lookup(prefix + envHealthPath)
        • What: Defines val, ok.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L454: upstream.HealthPath = ensureLeadingSlash(strings.TrimSpace(val))
        • What: Assigns upstream.HealthPath.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L457: if val, ok := lookup(prefix + envTLSEnabled); ok && strings.TrimSpace(val) != "" { enabled, err := strconv.ParseBool(strings.TrimSpace(val)…
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L457: val, ok := lookup(prefix + envTLSEnabled)
        • What: Defines val, ok.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L458: enabled, err := strconv.ParseBool(strings.TrimSpace(val))
        • What: Defines enabled, err.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L459: if err != nil { return fmt.Errorf("invalid %s%s: %w", prefix, envTLSEnabled, err) }
        • What: Branches conditionally.
        • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L460: return fmt.Errorf("invalid %s%s: %w", prefix, envTLSEnabled, err)
            • What: Returns from the current function.
            • Why: Ends the current execution path and hands control back to the caller.
            • How: Executes a return statement (possibly returning values).
      • L462: upstream.TLS.Enabled = enabled
        • What: Assigns upstream.TLS.Enabled.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L465: if val, ok := lookup(prefix + envTLSInsecureSkipVerify); ok && strings.TrimSpace(val) != "" { enabled, err := strconv.ParseBool(strings.Tri…
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L465: val, ok := lookup(prefix + envTLSInsecureSkipVerify)
        • What: Defines val, ok.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L466: enabled, err := strconv.ParseBool(strings.TrimSpace(val))
        • What: Defines enabled, err.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L467: if err != nil { return fmt.Errorf("invalid %s%s: %w", prefix, envTLSInsecureSkipVerify, err) }
        • What: Branches conditionally.
        • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L468: return fmt.Errorf("invalid %s%s: %w", prefix, envTLSInsecureSkipVerify, err)
            • What: Returns from the current function.
            • Why: Ends the current execution path and hands control back to the caller.
            • How: Executes a return statement (possibly returning values).
      • L470: upstream.TLS.InsecureSkipVerify = enabled
        • What: Assigns upstream.TLS.InsecureSkipVerify.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L471: if enabled { upstream.TLS.Enabled = true }
        • What: Branches conditionally.
        • Why: Handles different execution paths based on runtime state.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L472: upstream.TLS.Enabled = true
            • What: Assigns upstream.TLS.Enabled.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L476: if val, ok := lookup(prefix + envTLSCAFile); ok && strings.TrimSpace(val) != "" { upstream.TLS.CAFile = strings.TrimSpace(val) upstream.TLS…
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L476: val, ok := lookup(prefix + envTLSCAFile)
        • What: Defines val, ok.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L477: upstream.TLS.CAFile = strings.TrimSpace(val)
        • What: Assigns upstream.TLS.CAFile.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L478: upstream.TLS.Enabled = true
        • What: Assigns upstream.TLS.Enabled.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L480: if val, ok := lookup(prefix + envTLSCertFile); ok && strings.TrimSpace(val) != "" { upstream.TLS.ClientCertFile = strings.TrimSpace(val) up…
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L480: val, ok := lookup(prefix + envTLSCertFile)
        • What: Defines val, ok.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L481: upstream.TLS.ClientCertFile = strings.TrimSpace(val)
        • What: Assigns upstream.TLS.ClientCertFile.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L482: upstream.TLS.Enabled = true
        • What: Assigns upstream.TLS.Enabled.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L484: if val, ok := lookup(prefix + envTLSKeyFile); ok && strings.TrimSpace(val) != "" { upstream.TLS.ClientKeyFile = strings.TrimSpace(val) upst…
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L484: val, ok := lookup(prefix + envTLSKeyFile)
        • What: Defines val, ok.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L485: upstream.TLS.ClientKeyFile = strings.TrimSpace(val)
        • What: Assigns upstream.TLS.ClientKeyFile.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L486: upstream.TLS.Enabled = true
        • What: Assigns upstream.TLS.Enabled.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L489: return nil
    • What: Returns from the current function.
    • Why: Ends the current execution path and hands control back to the caller.
    • How: Executes a return statement (possibly returning values).

(*Config).normalize

What: Fills in derived defaults and canonicalizes fields after YAML/env overrides.

Why: Config inputs can be partial and inconsistent (missing slashes, empty defaults). Normalization makes downstream behavior predictable.

How: Defaults numeric/time fields, ensures required upstream entries exist, canonicalizes health paths, reconciles TLS flags, and normalizes webhook endpoint values.

pkg/gateway/config/config.go#L493
func (cfg *Config) normalize() error {
if cfg.HTTP.Port == 0 {
cfg.HTTP.Port = defaultPort
}
if cfg.HTTP.ShutdownTimeout.AsDuration() <= 0 {
cfg.HTTP.ShutdownTimeout = DurationFrom(defaultShutdownTimeout)
}
if cfg.Readiness.Timeout.AsDuration() <= 0 {
cfg.Readiness.Timeout = DurationFrom(defaultReadinessTimeout)
}
if strings.TrimSpace(cfg.Readiness.UserAgent) == "" {
cfg.Readiness.UserAgent = defaultReadinessUserAgent
}
if cfg.RateLimit.Window.AsDuration() <= 0 {
cfg.RateLimit.Window = DurationFrom(defaultRateLimitWindow)
}
if cfg.RateLimit.Max <= 0 {
cfg.RateLimit.Max = defaultRateLimitMax
}

if strings.TrimSpace(cfg.Admin.Listen) == "" {
cfg.Admin.Listen = defaultAdminListen
}

if cfg.WebSocket.IdleTimeout.AsDuration() <= 0 {
cfg.WebSocket.IdleTimeout = DurationFrom(defaultWebSocketIdleTimeout)
}
if cfg.WebSocket.MaxConcurrent < 0 {
cfg.WebSocket.MaxConcurrent = defaultWebSocketMaxConcurrent
}

cfg.ensureUpstream(envTradePrefix)
cfg.ensureUpstream(envTaskPrefix)

for i := range cfg.Readiness.Upstreams {
if strings.TrimSpace(cfg.Readiness.Upstreams[i].HealthPath) == "" {
cfg.Readiness.Upstreams[i].HealthPath = defaultHealthPath
} else {
cfg.Readiness.Upstreams[i].HealthPath = ensureLeadingSlash(cfg.Readiness.Upstreams[i].HealthPath)
}
if cfg.Readiness.Upstreams[i].TLS.InsecureSkipVerify {
cfg.Readiness.Upstreams[i].TLS.Enabled = true
}
}

for i := range cfg.Webhooks.Endpoints {
cfg.Webhooks.Endpoints[i].Name = strings.ToLower(strings.TrimSpace(cfg.Webhooks.Endpoints[i].Name))
cfg.Webhooks.Endpoints[i].Path = ensureLeadingSlash(strings.TrimSpace(cfg.Webhooks.Endpoints[i].Path))
if strings.TrimSpace(cfg.Webhooks.Endpoints[i].SignatureHeader) == "" {
cfg.Webhooks.Endpoints[i].SignatureHeader = defaultWebhookSignatureHeader
}
if cfg.Webhooks.Endpoints[i].MaxAttempts <= 0 {
cfg.Webhooks.Endpoints[i].MaxAttempts = defaultWebhookMaxAttempts
}
if cfg.Webhooks.Endpoints[i].InitialBackoff.AsDuration() <= 0 {
cfg.Webhooks.Endpoints[i].InitialBackoff = DurationFrom(defaultWebhookBackoff)
}
if cfg.Webhooks.Endpoints[i].Timeout.AsDuration() <= 0 {
cfg.Webhooks.Endpoints[i].Timeout = DurationFrom(defaultWebhookTimeout)
}
}

return nil
}

Walkthrough

Expand walkthrough (38 steps)

The list below documents the statements inside the function body, including nested blocks and inline closures.

  • L494: if cfg.HTTP.Port == 0 { cfg.HTTP.Port = defaultPort }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L495: cfg.HTTP.Port = defaultPort
        • What: Assigns cfg.HTTP.Port.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L497: if cfg.HTTP.ShutdownTimeout.AsDuration() <= 0 { cfg.HTTP.ShutdownTimeout = DurationFrom(defaultShutdownTimeout) }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L498: cfg.HTTP.ShutdownTimeout = DurationFrom(defaultShutdownTimeout)
        • What: Assigns cfg.HTTP.ShutdownTimeout.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L500: if cfg.Readiness.Timeout.AsDuration() <= 0 { cfg.Readiness.Timeout = DurationFrom(defaultReadinessTimeout) }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L501: cfg.Readiness.Timeout = DurationFrom(defaultReadinessTimeout)
        • What: Assigns cfg.Readiness.Timeout.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L503: if strings.TrimSpace(cfg.Readiness.UserAgent) == "" { cfg.Readiness.UserAgent = defaultReadinessUserAgent }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L504: cfg.Readiness.UserAgent = defaultReadinessUserAgent
        • What: Assigns cfg.Readiness.UserAgent.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L506: if cfg.RateLimit.Window.AsDuration() <= 0 { cfg.RateLimit.Window = DurationFrom(defaultRateLimitWindow) }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L507: cfg.RateLimit.Window = DurationFrom(defaultRateLimitWindow)
        • What: Assigns cfg.RateLimit.Window.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L509: if cfg.RateLimit.Max <= 0 { cfg.RateLimit.Max = defaultRateLimitMax }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L510: cfg.RateLimit.Max = defaultRateLimitMax
        • What: Assigns cfg.RateLimit.Max.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L513: if strings.TrimSpace(cfg.Admin.Listen) == "" { cfg.Admin.Listen = defaultAdminListen }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L514: cfg.Admin.Listen = defaultAdminListen
        • What: Assigns cfg.Admin.Listen.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L517: if cfg.WebSocket.IdleTimeout.AsDuration() <= 0 { cfg.WebSocket.IdleTimeout = DurationFrom(defaultWebSocketIdleTimeout) }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L518: cfg.WebSocket.IdleTimeout = DurationFrom(defaultWebSocketIdleTimeout)
        • What: Assigns cfg.WebSocket.IdleTimeout.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L520: if cfg.WebSocket.MaxConcurrent < 0 { cfg.WebSocket.MaxConcurrent = defaultWebSocketMaxConcurrent }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L521: cfg.WebSocket.MaxConcurrent = defaultWebSocketMaxConcurrent
        • What: Assigns cfg.WebSocket.MaxConcurrent.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L524: cfg.ensureUpstream(envTradePrefix)
    • What: Calls cfg.ensureUpstream.
    • Why: Performs side effects or delegates work to a helper.
    • How: Executes the expression statement.
  • L525: cfg.ensureUpstream(envTaskPrefix)
    • What: Calls cfg.ensureUpstream.
    • Why: Performs side effects or delegates work to a helper.
    • How: Executes the expression statement.
  • L527: for i := range cfg.Readiness.Upstreams { if strings.TrimSpace(cfg.Readiness.Upstreams[i].HealthPath) == "" { cfg.Readiness.Upstreams[i].Hea…
    • What: Iterates over a collection.
    • Why: Processes multiple elements with the same logic.
    • How: Executes a for ... range loop.
    • Nested steps:
      • L528: if strings.TrimSpace(cfg.Readiness.Upstreams[i].HealthPath) == "" { cfg.Readiness.Upstreams[i].HealthPath = defaultHealthPath } else { cfg.…
        • What: Branches conditionally.
        • Why: Handles different execution paths based on runtime state.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L529: cfg.Readiness.Upstreams[i].HealthPath = defaultHealthPath
            • What: Assigns cfg.Readiness.Upstreams[i].HealthPath.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
          • L531: cfg.Readiness.Upstreams[i].HealthPath = ensureLeadingSlash(cfg.Readiness.Upstreams[i].HealthPath)
            • What: Assigns cfg.Readiness.Upstreams[i].HealthPath.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L533: if cfg.Readiness.Upstreams[i].TLS.InsecureSkipVerify { cfg.Readiness.Upstreams[i].TLS.Enabled = true }
        • What: Branches conditionally.
        • Why: Handles different execution paths based on runtime state.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L534: cfg.Readiness.Upstreams[i].TLS.Enabled = true
            • What: Assigns cfg.Readiness.Upstreams[i].TLS.Enabled.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L538: for i := range cfg.Webhooks.Endpoints { cfg.Webhooks.Endpoints[i].Name = strings.ToLower(strings.TrimSpace(cfg.Webhooks.Endpoints[i].Name))…
    • What: Iterates over a collection.
    • Why: Processes multiple elements with the same logic.
    • How: Executes a for ... range loop.
    • Nested steps:
      • L539: cfg.Webhooks.Endpoints[i].Name = strings.ToLower(strings.TrimSpace(cfg.Webhooks.Endpoints[i].Name))
        • What: Assigns cfg.Webhooks.Endpoints[i].Name.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L540: cfg.Webhooks.Endpoints[i].Path = ensureLeadingSlash(strings.TrimSpace(cfg.Webhooks.Endpoints[i].Path))
        • What: Assigns cfg.Webhooks.Endpoints[i].Path.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L541: if strings.TrimSpace(cfg.Webhooks.Endpoints[i].SignatureHeader) == "" { cfg.Webhooks.Endpoints[i].SignatureHeader = defaultWebhookSignature…
        • What: Branches conditionally.
        • Why: Handles different execution paths based on runtime state.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L542: cfg.Webhooks.Endpoints[i].SignatureHeader = defaultWebhookSignatureHeader
            • What: Assigns cfg.Webhooks.Endpoints[i].SignatureHeader.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L544: if cfg.Webhooks.Endpoints[i].MaxAttempts <= 0 { cfg.Webhooks.Endpoints[i].MaxAttempts = defaultWebhookMaxAttempts }
        • What: Branches conditionally.
        • Why: Handles different execution paths based on runtime state.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L545: cfg.Webhooks.Endpoints[i].MaxAttempts = defaultWebhookMaxAttempts
            • What: Assigns cfg.Webhooks.Endpoints[i].MaxAttempts.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L547: if cfg.Webhooks.Endpoints[i].InitialBackoff.AsDuration() <= 0 { cfg.Webhooks.Endpoints[i].InitialBackoff = DurationFrom(defaultWebhookBacko…
        • What: Branches conditionally.
        • Why: Handles different execution paths based on runtime state.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L548: cfg.Webhooks.Endpoints[i].InitialBackoff = DurationFrom(defaultWebhookBackoff)
            • What: Assigns cfg.Webhooks.Endpoints[i].InitialBackoff.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L550: if cfg.Webhooks.Endpoints[i].Timeout.AsDuration() <= 0 { cfg.Webhooks.Endpoints[i].Timeout = DurationFrom(defaultWebhookTimeout) }
        • What: Branches conditionally.
        • Why: Handles different execution paths based on runtime state.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L551: cfg.Webhooks.Endpoints[i].Timeout = DurationFrom(defaultWebhookTimeout)
            • What: Assigns cfg.Webhooks.Endpoints[i].Timeout.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L555: return nil
    • What: Returns from the current function.
    • Why: Ends the current execution path and hands control back to the caller.
    • How: Executes a return statement (possibly returning values).

(Config).Validate

What: Performs semantic validation of configuration values.

Why: Failing fast prevents partial startup and reduces runtime surprises.

How: Checks ports/timeouts, enforces required upstreams and unique names, validates URLs and TLS cert/key pairing, validates admin allowlist values, and validates websocket/webhook settings; returns errors.Join for multiple failures.

pkg/gateway/config/config.go#L559
func (cfg Config) Validate() error {
var errs []error

if cfg.HTTP.Port <= 0 {
errs = append(errs, fmt.Errorf("http.port must be positive"))
}
if cfg.HTTP.ShutdownTimeout.AsDuration() <= 0 {
errs = append(errs, fmt.Errorf("http.shutdownTimeout must be positive"))
}
if cfg.Readiness.Timeout.AsDuration() <= 0 {
errs = append(errs, fmt.Errorf("readiness.timeout must be positive"))
}
if len(cfg.Readiness.Upstreams) == 0 {
errs = append(errs, fmt.Errorf("at least one readiness upstream required"))
}

requiredUpstreams := map[string]bool{"trade": false, "task": false}
seen := make(map[string]struct{})
for _, upstream := range cfg.Readiness.Upstreams {
name := strings.TrimSpace(strings.ToLower(upstream.Name))
if name == "" {
errs = append(errs, fmt.Errorf("readiness upstream name must not be empty"))
continue
}
if _, exists := seen[name]; exists {
errs = append(errs, fmt.Errorf("duplicate readiness upstream name: %s", upstream.Name))
continue
}
seen[name] = struct{}{}
if upstream.BaseURL == "" {
errs = append(errs, fmt.Errorf("readiness upstream %s requires baseURL", upstream.Name))
} else if _, err := url.ParseRequestURI(upstream.BaseURL); err != nil {
errs = append(errs, fmt.Errorf("readiness upstream %s baseURL invalid: %w", upstream.Name, err))
}
if upstream.TLS.ClientCertFile != "" && upstream.TLS.ClientKeyFile == "" {
errs = append(errs, fmt.Errorf("readiness upstream %s tls client key required when cert provided", upstream.Name))
}
if upstream.TLS.ClientKeyFile != "" && upstream.TLS.ClientCertFile == "" {
errs = append(errs, fmt.Errorf("readiness upstream %s tls client cert required when key provided", upstream.Name))
}
if _, ok := requiredUpstreams[name]; ok {
requiredUpstreams[name] = true
}
}

for key, satisfied := range requiredUpstreams {
if !satisfied {
errs = append(errs, fmt.Errorf("%s upstream configuration is required", key))
}
}

if cfg.RateLimit.Max <= 0 {
errs = append(errs, fmt.Errorf("rateLimit.max must be positive"))
}
if cfg.RateLimit.Window.AsDuration() <= 0 {
errs = append(errs, fmt.Errorf("rateLimit.window must be positive"))
}

if cfg.Admin.Enabled {
if strings.TrimSpace(cfg.Admin.Listen) == "" {
errs = append(errs, fmt.Errorf("admin.listen must be provided when admin.enabled is true"))
}
for _, entry := range cfg.Admin.Allow {
e := strings.TrimSpace(entry)
if e == "" {
continue
}
if strings.Contains(e, "/") {
if _, err := netip.ParsePrefix(e); err != nil {
errs = append(errs, fmt.Errorf("invalid admin allow value %q: %w", e, err))
}
} else if _, err := netip.ParseAddr(e); err != nil {
errs = append(errs, fmt.Errorf("invalid admin allow value %q: %w", e, err))
}
}
}

if cfg.WebSocket.MaxConcurrent < 0 {
errs = append(errs, fmt.Errorf("websocket.maxConcurrent cannot be negative"))
}
if cfg.WebSocket.IdleTimeout.AsDuration() < 0 {
errs = append(errs, fmt.Errorf("websocket.idleTimeout cannot be negative"))
}

if cfg.Webhooks.Enabled {
if len(cfg.Webhooks.Endpoints) == 0 {
errs = append(errs, fmt.Errorf("webhooks.enabled is true but no endpoints configured"))
}
seenWebhookNames := make(map[string]struct{})
seenWebhookPaths := make(map[string]struct{})
for _, endpoint := range cfg.Webhooks.Endpoints {
name := strings.TrimSpace(endpoint.Name)
if name == "" {
errs = append(errs, fmt.Errorf("webhook endpoint name must be provided"))
} else {
if _, exists := seenWebhookNames[name]; exists {
errs = append(errs, fmt.Errorf("duplicate webhook endpoint name: %s", name))
}
seenWebhookNames[name] = struct{}{}
}

path := strings.TrimSpace(endpoint.Path)
if path == "" || path == "/" {
errs = append(errs, fmt.Errorf("webhook endpoint %s must specify a path", name))
} else {
if _, exists := seenWebhookPaths[path]; exists {
errs = append(errs, fmt.Errorf("duplicate webhook endpoint path: %s", path))
}
seenWebhookPaths[path] = struct{}{}
}

if strings.TrimSpace(endpoint.TargetURL) == "" {
errs = append(errs, fmt.Errorf("webhook endpoint %s targetURL is required", name))
} else if _, err := url.ParseRequestURI(endpoint.TargetURL); err != nil {
errs = append(errs, fmt.Errorf("webhook endpoint %s targetURL invalid: %w", name, err))
}

if strings.TrimSpace(endpoint.Secret) == "" {
errs = append(errs, fmt.Errorf("webhook endpoint %s secret is required", name))
}

if endpoint.MaxAttempts <= 0 {
errs = append(errs, fmt.Errorf("webhook endpoint %s maxAttempts must be positive", name))
}

if endpoint.InitialBackoff.AsDuration() <= 0 {
errs = append(errs, fmt.Errorf("webhook endpoint %s initialBackoff must be positive", name))
}
if endpoint.Timeout.AsDuration() <= 0 {
errs = append(errs, fmt.Errorf("webhook endpoint %s timeout must be positive", name))
}
}
}

if len(errs) == 0 {
return nil
}
return errors.Join(errs...)
}

Walkthrough

Expand walkthrough (94 steps)

The list below documents the statements inside the function body, including nested blocks and inline closures.

  • L560: var errs []error
    • What: Declares local names.
    • Why: Introduces variables or types used later in the function.
    • How: Executes a Go declaration statement inside the function body.
  • L562: if cfg.HTTP.Port <= 0 { errs = append(errs, fmt.Errorf("http.port must be positive")) }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L563: errs = append(errs, fmt.Errorf("http.port must be positive"))
        • What: Assigns errs.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L565: if cfg.HTTP.ShutdownTimeout.AsDuration() <= 0 { errs = append(errs, fmt.Errorf("http.shutdownTimeout must be positive")) }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L566: errs = append(errs, fmt.Errorf("http.shutdownTimeout must be positive"))
        • What: Assigns errs.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L568: if cfg.Readiness.Timeout.AsDuration() <= 0 { errs = append(errs, fmt.Errorf("readiness.timeout must be positive")) }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L569: errs = append(errs, fmt.Errorf("readiness.timeout must be positive"))
        • What: Assigns errs.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L571: if len(cfg.Readiness.Upstreams) == 0 { errs = append(errs, fmt.Errorf("at least one readiness upstream required")) }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L572: errs = append(errs, fmt.Errorf("at least one readiness upstream required"))
        • What: Assigns errs.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L575: requiredUpstreams := map[string]bool{"trade": false, "task": false}
    • What: Defines requiredUpstreams.
    • Why: Keeps intermediate state available for later steps in the function.
    • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L576: seen := make(map[string]struct{})
    • What: Defines seen.
    • Why: Keeps intermediate state available for later steps in the function.
    • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L577: for _, upstream := range cfg.Readiness.Upstreams { name := strings.TrimSpace(strings.ToLower(upstream.Name)) if name == "" { errs = append(…
    • What: Iterates over a collection.
    • Why: Processes multiple elements with the same logic.
    • How: Executes a for ... range loop.
    • Nested steps:
      • L578: name := strings.TrimSpace(strings.ToLower(upstream.Name))
        • What: Defines name.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L579: if name == "" { errs = append(errs, fmt.Errorf("readiness upstream name must not be empty")) continue }
        • What: Branches conditionally.
        • Why: Handles different execution paths based on runtime state.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L580: errs = append(errs, fmt.Errorf("readiness upstream name must not be empty"))
            • What: Assigns errs.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
          • L581: continue
            • What: Executes a statement.
            • Why: Advances the function logic.
            • How: Runs this statement as part of the function body.
      • L583: if _, exists := seen[name]; exists { errs = append(errs, fmt.Errorf("duplicate readiness upstream name: %s", upstream.Name)) continue }
        • What: Branches conditionally.
        • Why: Handles different execution paths based on runtime state.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L583: _, exists := seen[name]
            • What: Defines _, exists.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
          • L584: errs = append(errs, fmt.Errorf("duplicate readiness upstream name: %s", upstream.Name))
            • What: Assigns errs.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
          • L585: continue
            • What: Executes a statement.
            • Why: Advances the function logic.
            • How: Runs this statement as part of the function body.
      • L587: seen[name] = struct{}{}
        • What: Assigns seen[name].
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L588: if upstream.BaseURL == "" { errs = append(errs, fmt.Errorf("readiness upstream %s requires baseURL", upstream.Name)) } else if _, err := ur…
        • What: Branches conditionally.
        • Why: Handles different execution paths based on runtime state.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L589: errs = append(errs, fmt.Errorf("readiness upstream %s requires baseURL", upstream.Name))
            • What: Assigns errs.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
          • L590: if _, err := url.ParseRequestURI(upstream.BaseURL); err != nil { errs = append(errs, fmt.Errorf("readiness upstream %s baseURL invalid: %w"…
            • What: Branches conditionally.
            • Why: Handles different execution paths based on runtime state.
            • How: Evaluates the condition and executes the matching branch.
            • Nested steps:
              • L590: _, err := url.ParseRequestURI(upstream.BaseURL)
                • What: Defines _, err.
                • Why: Keeps intermediate state available for later steps in the function.
                • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
              • L591: errs = append(errs, fmt.Errorf("readiness upstream %s baseURL invalid: %w", upstream.Name, err))
                • What: Assigns errs.
                • Why: Keeps intermediate state available for later steps in the function.
                • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L593: if upstream.TLS.ClientCertFile != "" && upstream.TLS.ClientKeyFile == "" { errs = append(errs, fmt.Errorf("readiness upstream %s tls client…
        • What: Branches conditionally.
        • Why: Handles different execution paths based on runtime state.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L594: errs = append(errs, fmt.Errorf("readiness upstream %s tls client key required when cert provided", upstream.Name))
            • What: Assigns errs.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L596: if upstream.TLS.ClientKeyFile != "" && upstream.TLS.ClientCertFile == "" { errs = append(errs, fmt.Errorf("readiness upstream %s tls client…
        • What: Branches conditionally.
        • Why: Handles different execution paths based on runtime state.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L597: errs = append(errs, fmt.Errorf("readiness upstream %s tls client cert required when key provided", upstream.Name))
            • What: Assigns errs.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L599: if _, ok := requiredUpstreams[name]; ok { requiredUpstreams[name] = true }
        • What: Branches conditionally.
        • Why: Handles different execution paths based on runtime state.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L599: _, ok := requiredUpstreams[name]
            • What: Defines _, ok.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
          • L600: requiredUpstreams[name] = true
            • What: Assigns requiredUpstreams[name].
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L604: for key, satisfied := range requiredUpstreams { if !satisfied { errs = append(errs, fmt.Errorf("%s upstream configuration is required", key…
    • What: Iterates over a collection.
    • Why: Processes multiple elements with the same logic.
    • How: Executes a for ... range loop.
    • Nested steps:
      • L605: if !satisfied { errs = append(errs, fmt.Errorf("%s upstream configuration is required", key)) }
        • What: Branches conditionally.
        • Why: Handles different execution paths based on runtime state.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L606: errs = append(errs, fmt.Errorf("%s upstream configuration is required", key))
            • What: Assigns errs.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L610: if cfg.RateLimit.Max <= 0 { errs = append(errs, fmt.Errorf("rateLimit.max must be positive")) }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L611: errs = append(errs, fmt.Errorf("rateLimit.max must be positive"))
        • What: Assigns errs.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L613: if cfg.RateLimit.Window.AsDuration() <= 0 { errs = append(errs, fmt.Errorf("rateLimit.window must be positive")) }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L614: errs = append(errs, fmt.Errorf("rateLimit.window must be positive"))
        • What: Assigns errs.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L617: if cfg.Admin.Enabled { if strings.TrimSpace(cfg.Admin.Listen) == "" { errs = append(errs, fmt.Errorf("admin.listen must be provided when ad…
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L618: if strings.TrimSpace(cfg.Admin.Listen) == "" { errs = append(errs, fmt.Errorf("admin.listen must be provided when admin.enabled is true")) }
        • What: Branches conditionally.
        • Why: Handles different execution paths based on runtime state.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L619: errs = append(errs, fmt.Errorf("admin.listen must be provided when admin.enabled is true"))
            • What: Assigns errs.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L621: for _, entry := range cfg.Admin.Allow { e := strings.TrimSpace(entry) if e == "" { continue } if strings.Contains(e, "/") { if _, err := ne…
        • What: Iterates over a collection.
        • Why: Processes multiple elements with the same logic.
        • How: Executes a for ... range loop.
        • Nested steps:
          • L622: e := strings.TrimSpace(entry)
            • What: Defines e.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
          • L623: if e == "" { continue }
            • What: Branches conditionally.
            • Why: Handles different execution paths based on runtime state.
            • How: Evaluates the condition and executes the matching branch.
            • Nested steps:
              • L624: continue
                • What: Executes a statement.
                • Why: Advances the function logic.
                • How: Runs this statement as part of the function body.
          • L626: if strings.Contains(e, "/") { if _, err := netip.ParsePrefix(e); err != nil { errs = append(errs, fmt.Errorf("invalid admin allow value %q:…
            • What: Branches conditionally.
            • Why: Handles different execution paths based on runtime state.
            • How: Evaluates the condition and executes the matching branch.
            • Nested steps:
              • L627: if _, err := netip.ParsePrefix(e); err != nil { errs = append(errs, fmt.Errorf("invalid admin allow value %q: %w", e, err)) }
                • What: Branches conditionally.
                • Why: Handles different execution paths based on runtime state.
                • How: Evaluates the condition and executes the matching branch.
                • Nested steps:
                  • L627: _, err := netip.ParsePrefix(e)
                    • What: Defines _, err.
                    • Why: Keeps intermediate state available for later steps in the function.
                    • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
                  • L628: errs = append(errs, fmt.Errorf("invalid admin allow value %q: %w", e, err))
                    • What: Assigns errs.
                    • Why: Keeps intermediate state available for later steps in the function.
                    • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
              • L630: if _, err := netip.ParseAddr(e); err != nil { errs = append(errs, fmt.Errorf("invalid admin allow value %q: %w", e, err)) }
                • What: Branches conditionally.
                • Why: Handles different execution paths based on runtime state.
                • How: Evaluates the condition and executes the matching branch.
                • Nested steps:
                  • L630: _, err := netip.ParseAddr(e)
                    • What: Defines _, err.
                    • Why: Keeps intermediate state available for later steps in the function.
                    • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
                  • L631: errs = append(errs, fmt.Errorf("invalid admin allow value %q: %w", e, err))
                    • What: Assigns errs.
                    • Why: Keeps intermediate state available for later steps in the function.
                    • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L636: if cfg.WebSocket.MaxConcurrent < 0 { errs = append(errs, fmt.Errorf("websocket.maxConcurrent cannot be negative")) }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L637: errs = append(errs, fmt.Errorf("websocket.maxConcurrent cannot be negative"))
        • What: Assigns errs.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L639: if cfg.WebSocket.IdleTimeout.AsDuration() < 0 { errs = append(errs, fmt.Errorf("websocket.idleTimeout cannot be negative")) }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L640: errs = append(errs, fmt.Errorf("websocket.idleTimeout cannot be negative"))
        • What: Assigns errs.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L643: if cfg.Webhooks.Enabled { if len(cfg.Webhooks.Endpoints) == 0 { errs = append(errs, fmt.Errorf("webhooks.enabled is true but no endpoints c…
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L644: if len(cfg.Webhooks.Endpoints) == 0 { errs = append(errs, fmt.Errorf("webhooks.enabled is true but no endpoints configured")) }
        • What: Branches conditionally.
        • Why: Handles different execution paths based on runtime state.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L645: errs = append(errs, fmt.Errorf("webhooks.enabled is true but no endpoints configured"))
            • What: Assigns errs.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L647: seenWebhookNames := make(map[string]struct{})
        • What: Defines seenWebhookNames.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L648: seenWebhookPaths := make(map[string]struct{})
        • What: Defines seenWebhookPaths.
        • Why: Keeps intermediate state available for later steps in the function.
        • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
      • L649: for _, endpoint := range cfg.Webhooks.Endpoints { name := strings.TrimSpace(endpoint.Name) if name == "" { errs = append(errs, fmt.Errorf("…
        • What: Iterates over a collection.
        • Why: Processes multiple elements with the same logic.
        • How: Executes a for ... range loop.
        • Nested steps:
          • L650: name := strings.TrimSpace(endpoint.Name)
            • What: Defines name.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
          • L651: if name == "" { errs = append(errs, fmt.Errorf("webhook endpoint name must be provided")) } else { if _, exists := seenWebhookNames[name]; …
            • What: Branches conditionally.
            • Why: Handles different execution paths based on runtime state.
            • How: Evaluates the condition and executes the matching branch.
            • Nested steps:
              • L652: errs = append(errs, fmt.Errorf("webhook endpoint name must be provided"))
                • What: Assigns errs.
                • Why: Keeps intermediate state available for later steps in the function.
                • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
              • L654: if _, exists := seenWebhookNames[name]; exists { errs = append(errs, fmt.Errorf("duplicate webhook endpoint name: %s", name)) }
                • What: Branches conditionally.
                • Why: Handles different execution paths based on runtime state.
                • How: Evaluates the condition and executes the matching branch.
                • Nested steps:
                  • L654: _, exists := seenWebhookNames[name]
                    • What: Defines _, exists.
                    • Why: Keeps intermediate state available for later steps in the function.
                    • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
                  • L655: errs = append(errs, fmt.Errorf("duplicate webhook endpoint name: %s", name))
                    • What: Assigns errs.
                    • Why: Keeps intermediate state available for later steps in the function.
                    • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
              • L657: seenWebhookNames[name] = struct{}{}
                • What: Assigns seenWebhookNames[name].
                • Why: Keeps intermediate state available for later steps in the function.
                • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
          • L660: path := strings.TrimSpace(endpoint.Path)
            • What: Defines path.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
          • L661: if path == "" || path == "/" { errs = append(errs, fmt.Errorf("webhook endpoint %s must specify a path", name)) } else { if _, exists := se…
            • What: Branches conditionally.
            • Why: Handles different execution paths based on runtime state.
            • How: Evaluates the condition and executes the matching branch.
            • Nested steps:
              • L662: errs = append(errs, fmt.Errorf("webhook endpoint %s must specify a path", name))
                • What: Assigns errs.
                • Why: Keeps intermediate state available for later steps in the function.
                • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
              • L664: if _, exists := seenWebhookPaths[path]; exists { errs = append(errs, fmt.Errorf("duplicate webhook endpoint path: %s", path)) }
                • What: Branches conditionally.
                • Why: Handles different execution paths based on runtime state.
                • How: Evaluates the condition and executes the matching branch.
                • Nested steps:
                  • L664: _, exists := seenWebhookPaths[path]
                    • What: Defines _, exists.
                    • Why: Keeps intermediate state available for later steps in the function.
                    • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
                  • L665: errs = append(errs, fmt.Errorf("duplicate webhook endpoint path: %s", path))
                    • What: Assigns errs.
                    • Why: Keeps intermediate state available for later steps in the function.
                    • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
              • L667: seenWebhookPaths[path] = struct{}{}
                • What: Assigns seenWebhookPaths[path].
                • Why: Keeps intermediate state available for later steps in the function.
                • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
          • L670: if strings.TrimSpace(endpoint.TargetURL) == "" { errs = append(errs, fmt.Errorf("webhook endpoint %s targetURL is required", name)) } else …
            • What: Branches conditionally.
            • Why: Handles different execution paths based on runtime state.
            • How: Evaluates the condition and executes the matching branch.
            • Nested steps:
              • L671: errs = append(errs, fmt.Errorf("webhook endpoint %s targetURL is required", name))
                • What: Assigns errs.
                • Why: Keeps intermediate state available for later steps in the function.
                • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
              • L672: if _, err := url.ParseRequestURI(endpoint.TargetURL); err != nil { errs = append(errs, fmt.Errorf("webhook endpoint %s targetURL invalid: %…
                • What: Branches conditionally.
                • Why: Handles different execution paths based on runtime state.
                • How: Evaluates the condition and executes the matching branch.
                • Nested steps:
                  • L672: _, err := url.ParseRequestURI(endpoint.TargetURL)
                    • What: Defines _, err.
                    • Why: Keeps intermediate state available for later steps in the function.
                    • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
                  • L673: errs = append(errs, fmt.Errorf("webhook endpoint %s targetURL invalid: %w", name, err))
                    • What: Assigns errs.
                    • Why: Keeps intermediate state available for later steps in the function.
                    • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
          • L676: if strings.TrimSpace(endpoint.Secret) == "" { errs = append(errs, fmt.Errorf("webhook endpoint %s secret is required", name)) }
            • What: Branches conditionally.
            • Why: Handles different execution paths based on runtime state.
            • How: Evaluates the condition and executes the matching branch.
            • Nested steps:
              • L677: errs = append(errs, fmt.Errorf("webhook endpoint %s secret is required", name))
                • What: Assigns errs.
                • Why: Keeps intermediate state available for later steps in the function.
                • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
          • L680: if endpoint.MaxAttempts <= 0 { errs = append(errs, fmt.Errorf("webhook endpoint %s maxAttempts must be positive", name)) }
            • What: Branches conditionally.
            • Why: Handles different execution paths based on runtime state.
            • How: Evaluates the condition and executes the matching branch.
            • Nested steps:
              • L681: errs = append(errs, fmt.Errorf("webhook endpoint %s maxAttempts must be positive", name))
                • What: Assigns errs.
                • Why: Keeps intermediate state available for later steps in the function.
                • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
          • L684: if endpoint.InitialBackoff.AsDuration() <= 0 { errs = append(errs, fmt.Errorf("webhook endpoint %s initialBackoff must be positive", name))…
            • What: Branches conditionally.
            • Why: Handles different execution paths based on runtime state.
            • How: Evaluates the condition and executes the matching branch.
            • Nested steps:
              • L685: errs = append(errs, fmt.Errorf("webhook endpoint %s initialBackoff must be positive", name))
                • What: Assigns errs.
                • Why: Keeps intermediate state available for later steps in the function.
                • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
          • L687: if endpoint.Timeout.AsDuration() <= 0 { errs = append(errs, fmt.Errorf("webhook endpoint %s timeout must be positive", name)) }
            • What: Branches conditionally.
            • Why: Handles different execution paths based on runtime state.
            • How: Evaluates the condition and executes the matching branch.
            • Nested steps:
              • L688: errs = append(errs, fmt.Errorf("webhook endpoint %s timeout must be positive", name))
                • What: Assigns errs.
                • Why: Keeps intermediate state available for later steps in the function.
                • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L693: if len(errs) == 0 { return nil }
    • What: Branches conditionally.
    • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L694: return nil
        • What: Returns from the current function.
        • Why: Ends the current execution path and hands control back to the caller.
        • How: Executes a return statement (possibly returning values).
  • L696: return errors.Join(errs...)
    • What: Returns from the current function.
    • Why: Ends the current execution path and hands control back to the caller.
    • How: Executes a return statement (possibly returning values).

(*Config).ensureUpstream

What: Ensures an upstream entry exists for the provided prefix/name and returns it.

Why: Env overrides must be able to target an upstream even if YAML omitted its entry.

How: Searches cfg.Readiness.Upstreams case-insensitively; if missing, appends a new UpstreamConfig with defaults.

pkg/gateway/config/config.go#L699
func (cfg *Config) ensureUpstream(prefix string) *UpstreamConfig {
name := strings.ToLower(prefix)
for i := range cfg.Readiness.Upstreams {
if strings.EqualFold(cfg.Readiness.Upstreams[i].Name, name) {
cfg.Readiness.Upstreams[i].Name = name
return &cfg.Readiness.Upstreams[i]
}
}

upstream := UpstreamConfig{
Name: name,
BaseURL: "",
HealthPath: defaultHealthPath,
}
cfg.Readiness.Upstreams = append(cfg.Readiness.Upstreams, upstream)
return &cfg.Readiness.Upstreams[len(cfg.Readiness.Upstreams)-1]
}

Walkthrough

The list below documents the statements inside the function body, including nested blocks and inline closures.

  • L700: name := strings.ToLower(prefix)
    • What: Defines name.
    • Why: Keeps intermediate state available for later steps in the function.
    • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L701: for i := range cfg.Readiness.Upstreams { if strings.EqualFold(cfg.Readiness.Upstreams[i].Name, name) { cfg.Readiness.Upstreams[i].Name = na…
    • What: Iterates over a collection.
    • Why: Processes multiple elements with the same logic.
    • How: Executes a for ... range loop.
    • Nested steps:
      • L702: if strings.EqualFold(cfg.Readiness.Upstreams[i].Name, name) { cfg.Readiness.Upstreams[i].Name = name return &cfg.Readiness.Upstreams[i] }
        • What: Branches conditionally.
        • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L703: cfg.Readiness.Upstreams[i].Name = name
            • What: Assigns cfg.Readiness.Upstreams[i].Name.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
          • L704: return &cfg.Readiness.Upstreams[i]
            • What: Returns from the current function.
            • Why: Ends the current execution path and hands control back to the caller.
            • How: Executes a return statement (possibly returning values).
  • L708: upstream := UpstreamConfig{ Name: name, BaseURL: "", HealthPath: defaultHealthPath, }
    • What: Defines upstream.
    • Why: Keeps intermediate state available for later steps in the function.
    • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L713: cfg.Readiness.Upstreams = append(cfg.Readiness.Upstreams, upstream)
    • What: Assigns cfg.Readiness.Upstreams.
    • Why: Keeps intermediate state available for later steps in the function.
    • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L714: return &cfg.Readiness.Upstreams[len(cfg.Readiness.Upstreams)-1]
    • What: Returns from the current function.
    • Why: Ends the current execution path and hands control back to the caller.
    • How: Executes a return statement (possibly returning values).

parsePositiveDurationMillis

What: Parses a millisecond duration env var into a time.Duration.

Why: Several env overrides use the *_MS convention for backwards compatibility and platform friendliness.

How: Parses an integer, rejects non-positive values, and multiplies by time.Millisecond.

pkg/gateway/config/config.go#L717
func parsePositiveDurationMillis(value string) (time.Duration, error) {
ms, err := strconv.Atoi(strings.TrimSpace(value))
if err != nil {
return 0, err
}
if ms <= 0 {
return 0, fmt.Errorf("value must be positive: %d", ms)
}
return time.Duration(ms) * time.Millisecond, nil
}

Walkthrough

The list below documents the statements inside the function body, including nested blocks and inline closures.

  • L718: ms, err := strconv.Atoi(strings.TrimSpace(value))
    • What: Defines ms, err.
    • Why: Keeps intermediate state available for later steps in the function.
    • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L719: if err != nil { return 0, err }
    • What: Branches conditionally.
    • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L720: return 0, err
        • What: Returns from the current function.
        • Why: Ends the current execution path and hands control back to the caller.
        • How: Executes a return statement (possibly returning values).
  • L722: if ms <= 0 { return 0, fmt.Errorf("value must be positive: %d", ms) }
    • What: Branches conditionally.
    • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L723: return 0, fmt.Errorf("value must be positive: %d", ms)
        • What: Returns from the current function.
        • Why: Ends the current execution path and hands control back to the caller.
        • How: Executes a return statement (possibly returning values).
  • L725: return time.Duration(ms) * time.Millisecond, nil
    • What: Returns from the current function.
    • Why: Ends the current execution path and hands control back to the caller.
    • How: Executes a return statement (possibly returning values).

splitAndTrim

What: Splits a delimited string into trimmed tokens (comma/space/semicolon separators).

Why: Many env vars accept lists (audiences, CORS origins, allowlist); this makes parsing consistent.

How: Uses strings.FieldsFunc and filters empty tokens.

pkg/gateway/config/config.go#L728
func splitAndTrim(value string) []string {
parts := strings.FieldsFunc(value, func(r rune) bool {
return r == ',' || r == ' ' || r == ';'
})
result := make([]string, 0, len(parts))
for _, part := range parts {
if trimmed := strings.TrimSpace(part); trimmed != "" {
result = append(result, trimmed)
}
}
return result
}

Walkthrough

The list below documents the statements inside the function body, including nested blocks and inline closures.

  • L729: parts := strings.FieldsFunc(value, func(r rune) bool { return r == ',' || r == ' ' || r == ';' })
    • What: Defines parts.
    • Why: Keeps intermediate state available for later steps in the function.
    • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
    • Nested steps:
      • L729: func(r rune) bool { return r == ',' || r == ' ' || r == ';' }
        • What: Defines an inline function (closure).
        • Why: Encapsulates callback logic and may capture variables from the surrounding scope.
        • How: Declares a func literal and uses it as a value (for example, as an HTTP handler or callback).
        • Nested steps:
          • L730: return r == ',' || r == ' ' || r == ';'
            • What: Returns from the current function.
            • Why: Ends the current execution path and hands control back to the caller.
            • How: Executes a return statement (possibly returning values).
  • L732: result := make([]string, 0, len(parts))
    • What: Defines result.
    • Why: Keeps intermediate state available for later steps in the function.
    • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L733: for _, part := range parts { if trimmed := strings.TrimSpace(part); trimmed != "" { result = append(result, trimmed) } }
    • What: Iterates over a collection.
    • Why: Processes multiple elements with the same logic.
    • How: Executes a for ... range loop.
    • Nested steps:
      • L734: if trimmed := strings.TrimSpace(part); trimmed != "" { result = append(result, trimmed) }
        • What: Branches conditionally.
        • Why: Handles different execution paths based on runtime state.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L734: trimmed := strings.TrimSpace(part)
            • What: Defines trimmed.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
          • L735: result = append(result, trimmed)
            • What: Assigns result.
            • Why: Keeps intermediate state available for later steps in the function.
            • How: Evaluates the right-hand side expressions and stores results in the left-hand variables.
  • L738: return result
    • What: Returns from the current function.
    • Why: Ends the current execution path and hands control back to the caller.
    • How: Executes a return statement (possibly returning values).

ensureLeadingSlash

What: Ensures a URL path begins with /.

Why: Normalizes config inputs so downstream routing/probing code can assume canonical paths.

How: Returns / for empty input, preserves already-slashed paths, otherwise prefixes /.

pkg/gateway/config/config.go#L741
func ensureLeadingSlash(path string) string {
if path == "" {
return "/"
}
if strings.HasPrefix(path, "/") {
return path
}
return "/" + path
}

Walkthrough

The list below documents the statements inside the function body, including nested blocks and inline closures.

  • L742: if path == "" { return "/" }
    • What: Branches conditionally.
    • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L743: return "/"
        • What: Returns from the current function.
        • Why: Ends the current execution path and hands control back to the caller.
        • How: Executes a return statement (possibly returning values).
  • L745: if strings.HasPrefix(path, "/") { return path }
    • What: Branches conditionally.
    • Why: Short-circuits early when a precondition is not met or an error/edge case is detected.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L746: return path
        • What: Returns from the current function.
        • Why: Ends the current execution path and hands control back to the caller.
        • How: Executes a return statement (possibly returning values).
  • L748: return "/" + path
    • What: Returns from the current function.
    • Why: Ends the current execution path and hands control back to the caller.
    • How: Executes a return statement (possibly returning values).

Start Here

Architecture

Guides

Reference

Neighboring source