Skip to main content

pkg/gateway/runtime/runtime.go

Source

Overview

What:

Composes configuration, readiness checking, metrics registry, and the HTTP server into a single lifecycle object (Runtime).

This package is the "composition root" for gateway execution: it builds the server and (optionally) an admin control-plane server.

Why:

The gateway needs a reusable runtime that can be:

  • started/stopped by the CLI
  • embedded as a library
  • managed by a daemon wrapper

Keeping lifecycle orchestration here avoids duplicating startup/shutdown/reload logic across entrypoints.

How:

  • New() builds the server, readiness checker, and metrics registry.
  • Start() runs the public server (and optionally the admin server) in the background.
  • Wait() blocks until shutdown and returns the terminal error.
  • Shutdown() requests graceful shutdown.
  • Reload() rebuilds dependencies with a new config (only when not running).

Notes: The admin server is intentionally separated from the public listener. It should be bound to loopback or protected by admin.token and allowlists.

Contents

Imports

import block 1

pkg/gateway/runtime/runtime.go#L6
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"

"github.com/theroutercompany/api_router/internal/platform/health"
gatewayconfig "github.com/theroutercompany/api_router/pkg/gateway/config"
gatewaymetrics "github.com/theroutercompany/api_router/pkg/gateway/metrics"
gatewayserver "github.com/theroutercompany/api_router/pkg/gateway/server"
pkglog "github.com/theroutercompany/api_router/pkg/log"
)

Variables

var block 1

pkg/gateway/runtime/runtime.go#L28
var (
// ErrAlreadyRunning indicates the runtime is already serving requests.
ErrAlreadyRunning = errors.New("runtime already running")
// ErrNotRunning indicates the runtime has not been started yet.
ErrNotRunning = errors.New("runtime not running")
// ErrReloadWhileRunning is returned when attempting to reload while serving.
ErrReloadWhileRunning = errors.New("cannot reload runtime while it is running")
)

ErrAlreadyRunning

What: Sentinel error returned when Start() is called while the runtime is already running.

Why: Prevents multiple goroutines from attempting to start/own the same server lifecycle.

How: Returned when Runtime.errCh is non-nil inside Start().

ErrNotRunning

What: Sentinel error returned when Wait() is called before the runtime has started.

Why: Makes lifecycle misuse explicit instead of blocking forever or panicking.

How: Returned when Runtime.errCh is nil inside Wait().

ErrReloadWhileRunning

What: Sentinel error returned when Reload() is called while the runtime is running.

Why: Hot-swapping server dependencies during active serving is unsafe; reload is only supported while stopped.

How: Returned when Runtime.errCh is non-nil inside Reload().

Types

type block 1

pkg/gateway/runtime/runtime.go#L38
type Runtime struct {
mu sync.Mutex

cfg gatewayconfig.Config
server *gatewayserver.Server
checker *health.Checker
registry *gatewaymetrics.Registry
reloadFn func() (gatewayconfig.Config, error)
adminAllow []*net.IPNet
bootTime time.Time
logger pkglog.Logger

baseCtx context.Context
cancel context.CancelFunc
errCh chan error
adminSrv *http.Server
adminErrCh chan error
adminAddr string
}

Runtime

What: The primary lifecycle object that owns the server, readiness checker, metrics registry, and admin server.

Why: Encapsulates concurrency, context cancellation, and shared state so entrypoints don't reimplement lifecycle wiring.

How: Uses a mutex to guard state transitions and stores channels/cancel funcs for start/wait/shutdown coordination.

type block 2

pkg/gateway/runtime/runtime.go#L59
type Option func(*Runtime)

Option

What: Functional option type for configuring Runtime construction.

Why: Keeps the New() signature stable while allowing opt-in behaviors (logger injection, reload callback).

How: Options mutate fields on the Runtime during New().

type block 3

pkg/gateway/runtime/runtime.go#L315
type upstreamTransport struct {
defaultTransport *http.Transport
transports map[string]*http.Transport
}

upstreamTransport

What: A custom http.RoundTripper that routes requests to host-specific *http.Transport instances.

Why: Per-upstream TLS settings require per-host transport configuration; a single transport cannot represent multiple TLS configs safely.

How: Implements RoundTrip and CloseIdleConnections and holds a default transport plus a host-to-transport map.

Functions and Methods

WithReloadFunc

What: Runtime option that registers a callback invoked by the admin server on reload requests.

Why: The runtime itself does not know how to re-read config (file watching, env layering, etc.); the caller provides that policy.

How: Sets Runtime.reloadFn, which is called by the POST /__admin/reload handler.

pkg/gateway/runtime/runtime.go#L62
func WithReloadFunc(fn func() (gatewayconfig.Config, error)) Option {
return func(r *Runtime) {
r.reloadFn = fn
}
}

Walkthrough

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

  • L63: return func(r *Runtime) { r.reloadFn = 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:
      • L63: func(r *Runtime) { r.reloadFn = 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:
          • L64: r.reloadFn = fn
            • What: Assigns r.reloadFn.
            • 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.

WithLogger

What: Runtime option that overrides the logger used by the runtime and underlying server.

Why: Allows CLIs/services to inject their own structured logger configuration.

How: Sets Runtime.logger when the provided logger is non-nil.

pkg/gateway/runtime/runtime.go#L69
func WithLogger(logger pkglog.Logger) Option {
return func(r *Runtime) {
if logger != nil {
r.logger = logger
}
}
}

Walkthrough

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

  • L70: return func(r *Runtime) { if logger != nil { r.logger = logger } }
    • 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:
      • L70: func(r *Runtime) { if logger != nil { r.logger = logger } }
        • 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:
          • L71: if logger != nil { r.logger = logger }
            • What: Branches conditionally.
            • Why: Handles different execution paths based on runtime state.
            • How: Evaluates the condition and executes the matching branch.
            • Nested steps:
              • L72: r.logger = logger
                • What: Assigns r.logger.
                • 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.

New

What: Constructs a Runtime from an already-loaded gatewayconfig.Config.

Why: Separates config loading from runtime composition so callers can control where config comes from (CLI, tests, embedding).

How: Initializes logger/boot time/admin allowlist, applies Options, then calls buildComponents to create the server/checker/metrics registry.

pkg/gateway/runtime/runtime.go#L78
func New(cfg gatewayconfig.Config, opts ...Option) (*Runtime, error) {
rt := &Runtime{
cfg: cfg,
adminAllow: parseAllowList(cfg.Admin.Allow),
bootTime: time.Now(),
logger: pkglog.Shared(),
}

for _, opt := range opts {
if opt != nil {
opt(rt)
}
}

if rt.logger == nil {
rt.logger = pkglog.Shared()
}

comps, err := buildComponents(cfg, rt.logger)
if err != nil {
return nil, err
}

rt.server = comps.server
rt.checker = comps.checker
rt.registry = comps.registry

return rt, nil
}

Walkthrough

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

  • L79: rt := &Runtime{ cfg: cfg, adminAllow: parseAllowList(cfg.Admin.Allow), bootTime: time.Now(), logger: pkglog.Shared(), }
    • What: Defines rt.
    • 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.
  • L86: for _, opt := range opts { if opt != nil { opt(rt) } }
    • What: Iterates over a collection.
    • Why: Processes multiple elements with the same logic.
    • How: Executes a for ... range loop.
    • Nested steps:
      • L87: if opt != nil { opt(rt) }
        • What: Branches conditionally.
        • Why: Handles different execution paths based on runtime state.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L88: opt(rt)
            • What: Calls opt.
            • Why: Performs side effects or delegates work to a helper.
            • How: Executes the expression statement.
  • L92: if rt.logger == nil { rt.logger = pkglog.Shared() }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L93: rt.logger = pkglog.Shared()
        • What: Assigns rt.logger.
        • 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.
  • L96: comps, err := buildComponents(cfg, rt.logger)
    • What: Defines comps, 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.
  • L97: if err != nil { return nil, 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:
      • L98: return nil, 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).
  • L101: rt.server = comps.server
    • What: Assigns rt.server.
    • 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.
  • L102: rt.checker = comps.checker
    • What: Assigns rt.checker.
    • 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.
  • L103: rt.registry = comps.registry
    • What: Assigns rt.registry.
    • 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.
  • L105: return rt, 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).

(*Runtime).Start

What: Starts serving the public gateway server (and optionally the admin server) in the background.

Why: Separates "start" from "wait" to support daemons and embedding where the caller controls the main loop.

How: Creates a derived context, starts gatewayserver.Server.Start in a goroutine, and conditionally starts the admin server based on config.

pkg/gateway/runtime/runtime.go#L109
func (r *Runtime) Start(ctx context.Context) error {
r.mu.Lock()
defer r.mu.Unlock()

if r.errCh != nil {
return ErrAlreadyRunning
}

if ctx == nil {
ctx = context.Background()
}

runCtx, cancel := context.WithCancel(ctx)
r.baseCtx = runCtx
r.cancel = cancel
r.errCh = make(chan error, 1)

go func() {
err := r.server.Start(runCtx)
r.errCh <- err
close(r.errCh)
}()

if r.cfg.Admin.Enabled {
if err := r.startAdminServer(runCtx); err != nil {
r.logger.Errorw("admin server failed to start", "error", err, "listen", r.cfg.Admin.Listen)
}
} else {
r.adminAddr = ""
}

return nil
}

Walkthrough

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

  • L110: r.mu.Lock()
    • What: Calls r.mu.Lock.
    • Why: Performs side effects or delegates work to a helper.
    • How: Executes the expression statement.
  • L111: defer r.mu.Unlock()
    • What: Defers a call for cleanup.
    • Why: Ensures the deferred action runs even on early returns.
    • How: Schedules the call to run when the surrounding function returns.
  • L113: if r.errCh != nil { return ErrAlreadyRunning }
    • 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:
      • L114: return ErrAlreadyRunning
        • 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).
  • L117: if ctx == nil { ctx = context.Background() }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L118: ctx = context.Background()
        • What: Assigns ctx.
        • 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.
  • L121: runCtx, cancel := context.WithCancel(ctx)
    • What: Defines runCtx, cancel.
    • 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.
  • L122: r.baseCtx = runCtx
    • What: Assigns r.baseCtx.
    • 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.
  • L123: r.cancel = cancel
    • What: Assigns r.cancel.
    • 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.
  • L124: r.errCh = make(chan error, 1)
    • What: Assigns r.errCh.
    • 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.
  • L126: go func() { err := r.server.Start(runCtx) r.errCh <- err close(r.errCh) }()
    • What: Starts a goroutine.
    • Why: Runs work concurrently.
    • How: Invokes the function call asynchronously using go.
    • Nested steps:
      • L126: func() { err := r.server.Start(runCtx) r.errCh <- err close(r.errCh) }
        • 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:
          • L127: err := r.server.Start(runCtx)
            • 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.
          • L128: r.errCh <- err
            • What: Sends a value on a channel.
            • Why: Communicates with another goroutine.
            • How: Executes a channel send operation.
          • L129: close(r.errCh)
            • What: Calls close.
            • Why: Performs side effects or delegates work to a helper.
            • How: Executes the expression statement.
  • L132: if r.cfg.Admin.Enabled { if err := r.startAdminServer(runCtx); err != nil { r.logger.Errorw("admin server failed to start", "error", err, "…
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L133: if err := r.startAdminServer(runCtx); err != nil { r.logger.Errorw("admin server failed to start", "error", err, "listen", r.cfg.Admin.List…
        • What: Branches conditionally.
        • Why: Handles different execution paths based on runtime state.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L133: err := r.startAdminServer(runCtx)
            • 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.
          • L134: r.logger.Errorw("admin server failed to start", "error", err, "listen", r.cfg.Admin.Listen)
            • What: Calls r.logger.Errorw.
            • Why: Performs side effects or delegates work to a helper.
            • How: Executes the expression statement.
      • L137: r.adminAddr = ""
        • What: Assigns r.adminAddr.
        • 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.
  • L140: 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).

(*Runtime).Wait

What: Blocks until the runtime stops and returns the terminal error.

Why: Provides a single place to normalize shutdown behavior and clean up internal state.

How: Waits for either server or admin errors, treats context.Canceled as nil, and resets internal fields (channels, cancel func, admin server state).

pkg/gateway/runtime/runtime.go#L144
func (r *Runtime) Wait() error {
r.mu.Lock()
errCh := r.errCh
adminErrCh := r.adminErrCh
r.mu.Unlock()

if errCh == nil {
return ErrNotRunning
}

var err error
select {
case err = <-errCh:
case adminErr := <-adminErrCh:
if adminErr != nil && !errors.Is(adminErr, http.ErrServerClosed) {
r.logger.Errorw("admin server stopped with error", "error", adminErr)
}
err = <-errCh
}

if errors.Is(err, context.Canceled) {
err = nil
}

r.mu.Lock()
r.errCh = nil
if r.cancel != nil {
r.cancel()
r.cancel = nil
}
if r.adminSrv != nil {
_ = r.adminSrv.Shutdown(context.Background())
}
r.adminSrv = nil
r.adminErrCh = nil
r.mu.Unlock()

return err
}

Walkthrough

Expand walkthrough (26 steps)

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

  • L145: r.mu.Lock()
    • What: Calls r.mu.Lock.
    • Why: Performs side effects or delegates work to a helper.
    • How: Executes the expression statement.
  • L146: errCh := r.errCh
    • What: Defines errCh.
    • 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.
  • L147: adminErrCh := r.adminErrCh
    • What: Defines adminErrCh.
    • 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.
  • L148: r.mu.Unlock()
    • What: Calls r.mu.Unlock.
    • Why: Performs side effects or delegates work to a helper.
    • How: Executes the expression statement.
  • L150: if errCh == nil { return ErrNotRunning }
    • 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:
      • L151: return ErrNotRunning
        • 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).
  • L154: var err 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.
  • L155: select { case err = <-errCh: case adminErr := <-adminErrCh: if adminErr != nil && !errors.Is(adminErr, http.ErrServerClosed) { r.logger.Err…
    • What: Selects among concurrent operations.
    • Why: Coordinates channel operations without blocking incorrectly.
    • How: Executes a select statement and runs one ready case.
    • Nested steps:
      • L156: case err = <-errCh:
        • What: Selects a select-case branch.
        • Why: Coordinates concurrent operations without blocking incorrectly.
        • How: Runs this case body when its channel operation is ready (or runs default immediately).
      • L157: case adminErr := <-adminErrCh:
        • What: Selects a select-case branch.
        • Why: Coordinates concurrent operations without blocking incorrectly.
        • How: Runs this case body when its channel operation is ready (or runs default immediately).
        • Nested steps:
          • L158: if adminErr != nil && !errors.Is(adminErr, http.ErrServerClosed) { r.logger.Errorw("admin server stopped with error", "error", adminErr) }
            • What: Branches conditionally.
            • Why: Handles different execution paths based on runtime state.
            • How: Evaluates the condition and executes the matching branch.
            • Nested steps:
              • L159: r.logger.Errorw("admin server stopped with error", "error", adminErr)
                • What: Calls r.logger.Errorw.
                • Why: Performs side effects or delegates work to a helper.
                • How: Executes the expression statement.
          • L161: err = <-errCh
            • What: Assigns 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.
  • L164: if errors.Is(err, context.Canceled) { 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:
      • L165: err = nil
        • What: Assigns 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.
  • L168: r.mu.Lock()
    • What: Calls r.mu.Lock.
    • Why: Performs side effects or delegates work to a helper.
    • How: Executes the expression statement.
  • L169: r.errCh = nil
    • What: Assigns r.errCh.
    • 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.
  • L170: if r.cancel != nil { r.cancel() r.cancel = nil }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L171: r.cancel()
        • What: Calls r.cancel.
        • Why: Performs side effects or delegates work to a helper.
        • How: Executes the expression statement.
      • L172: r.cancel = nil
        • What: Assigns r.cancel.
        • 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.
  • L174: if r.adminSrv != nil { _ = r.adminSrv.Shutdown(context.Background()) }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L175: _ = r.adminSrv.Shutdown(context.Background())
        • What: Assigns _.
        • 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.
  • L177: r.adminSrv = nil
    • What: Assigns r.adminSrv.
    • 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.
  • L178: r.adminErrCh = nil
    • What: Assigns r.adminErrCh.
    • 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.
  • L179: r.mu.Unlock()
    • What: Calls r.mu.Unlock.
    • Why: Performs side effects or delegates work to a helper.
    • How: Executes the expression statement.
  • L181: return 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).

(*Runtime).Run

What: Convenience method that calls Start(ctx) then Wait().

Why: Common CLI pattern; keeps call sites simple.

How: Delegates to Start and then blocks on Wait.

pkg/gateway/runtime/runtime.go#L185
func (r *Runtime) Run(ctx context.Context) error {
if err := r.Start(ctx); err != nil {
return err
}
return r.Wait()
}

Walkthrough

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

  • L186: if err := r.Start(ctx); err != nil { return 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:
      • L186: err := r.Start(ctx)
        • 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.
      • L187: return 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).
  • L189: return r.Wait()
    • 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).

(*Runtime).Shutdown

What: Requests graceful shutdown of the runtime when running.

Why: Provides a structured shutdown path for CLIs, daemons, and embedding (tests/servers).

How: Cancels the base context, shuts down the admin server (if present), then calls the underlying server's Shutdown(ctx).

pkg/gateway/runtime/runtime.go#L193
func (r *Runtime) Shutdown(ctx context.Context) error {
r.mu.Lock()
defer r.mu.Unlock()

if r.server == nil || r.errCh == nil {
return nil
}
if ctx == nil {
ctx = context.Background()
}

if r.cancel != nil {
r.cancel()
}

if r.adminSrv != nil {
_ = r.adminSrv.Shutdown(ctx)
r.adminSrv = nil
r.adminErrCh = nil
}

return r.server.Shutdown(ctx)
}

Walkthrough

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

  • L194: r.mu.Lock()
    • What: Calls r.mu.Lock.
    • Why: Performs side effects or delegates work to a helper.
    • How: Executes the expression statement.
  • L195: defer r.mu.Unlock()
    • What: Defers a call for cleanup.
    • Why: Ensures the deferred action runs even on early returns.
    • How: Schedules the call to run when the surrounding function returns.
  • L197: if r.server == nil || r.errCh == 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:
      • L198: 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).
  • L200: if ctx == nil { ctx = context.Background() }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L201: ctx = context.Background()
        • What: Assigns ctx.
        • 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: if r.cancel != nil { r.cancel() }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L205: r.cancel()
        • What: Calls r.cancel.
        • Why: Performs side effects or delegates work to a helper.
        • How: Executes the expression statement.
  • L208: if r.adminSrv != nil { _ = r.adminSrv.Shutdown(ctx) r.adminSrv = nil r.adminErrCh = nil }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L209: _ = r.adminSrv.Shutdown(ctx)
        • What: Assigns _.
        • 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.
      • L210: r.adminSrv = nil
        • What: Assigns r.adminSrv.
        • 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.
      • L211: r.adminErrCh = nil
        • What: Assigns r.adminErrCh.
        • 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.
  • L214: return r.server.Shutdown(ctx)
    • 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).

(*Runtime).Reload

What: Rebuilds runtime dependencies using a new configuration while the runtime is not running.

Why: Replacing server/checker/metrics while serving traffic is unsafe; reload is a controlled, stop-the-world operation.

How: Refuses when running (ErrReloadWhileRunning), calls buildComponents, then swaps cfg/server/checker/registry and recomputes the admin allowlist.

pkg/gateway/runtime/runtime.go#L218
func (r *Runtime) Reload(cfg gatewayconfig.Config) error {
r.mu.Lock()
defer r.mu.Unlock()

if r.errCh != nil {
return ErrReloadWhileRunning
}

comps, err := buildComponents(cfg, r.logger)
if err != nil {
return err
}

r.cfg = cfg
r.server = comps.server
r.checker = comps.checker
r.registry = comps.registry
r.adminAllow = parseAllowList(cfg.Admin.Allow)

return nil
}

Walkthrough

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

  • L219: r.mu.Lock()
    • What: Calls r.mu.Lock.
    • Why: Performs side effects or delegates work to a helper.
    • How: Executes the expression statement.
  • L220: defer r.mu.Unlock()
    • What: Defers a call for cleanup.
    • Why: Ensures the deferred action runs even on early returns.
    • How: Schedules the call to run when the surrounding function returns.
  • L222: if r.errCh != nil { return ErrReloadWhileRunning }
    • 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:
      • L223: return ErrReloadWhileRunning
        • 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).
  • L226: comps, err := buildComponents(cfg, r.logger)
    • What: Defines comps, 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.
  • L227: if err != nil { return 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:
      • L228: return 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).
  • L231: r.cfg = cfg
    • What: Assigns r.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.
  • L232: r.server = comps.server
    • What: Assigns r.server.
    • 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.
  • L233: r.checker = comps.checker
    • What: Assigns r.checker.
    • 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.
  • L234: r.registry = comps.registry
    • What: Assigns r.registry.
    • 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.
  • L235: r.adminAllow = parseAllowList(cfg.Admin.Allow)
    • What: Assigns r.adminAllow.
    • 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.
  • L237: 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).

(*Runtime).Config

What: Returns the runtime's current configuration snapshot.

Why: Allows admin/status handlers and callers to report current settings without exposing internal mutation.

How: Returns a copy of Runtime.cfg under the runtime mutex.

pkg/gateway/runtime/runtime.go#L241
func (r *Runtime) Config() gatewayconfig.Config {
r.mu.Lock()
defer r.mu.Unlock()
return r.cfg
}

Walkthrough

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

  • L242: r.mu.Lock()
    • What: Calls r.mu.Lock.
    • Why: Performs side effects or delegates work to a helper.
    • How: Executes the expression statement.
  • L243: defer r.mu.Unlock()
    • What: Defers a call for cleanup.
    • Why: Ensures the deferred action runs even on early returns.
    • How: Schedules the call to run when the surrounding function returns.
  • L244: return r.cfg
    • 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).

buildComponents

What: Internal helper that builds the server, readiness checker, and metrics registry from config.

Why: Keeps New() and Reload() small while centralizing dependency construction and invariants.

How: Builds a readiness http.Client (with per-upstream TLS transports), creates a health.Checker, optionally creates a metrics registry, then constructs gatewayserver.Server.

pkg/gateway/runtime/runtime.go#L247
func buildComponents(cfg gatewayconfig.Config, logger pkglog.Logger) (struct {
server *gatewayserver.Server
checker *health.Checker
registry *gatewaymetrics.Registry
}, error,
) {
readinessTimeout := cfg.Readiness.Timeout.AsDuration()
defaultTransport := defaultHTTPTransport()
hostTransports := make(map[string]*http.Transport)

upstreams := make([]health.Upstream, len(cfg.Readiness.Upstreams))
for i, upstreamCfg := range cfg.Readiness.Upstreams {
host, err := hostFromURL(upstreamCfg.BaseURL)
if err != nil {
return struct {
server *gatewayserver.Server
checker *health.Checker
registry *gatewaymetrics.Registry
}{}, fmt.Errorf("parse upstream %s base url: %w", upstreamCfg.Name, err)
}
if upstreamCfg.TLS.Enabled {
tlsCfg, err := buildReadinessTLSConfig(upstreamCfg.TLS)
if err != nil {
return struct {
server *gatewayserver.Server
checker *health.Checker
registry *gatewaymetrics.Registry
}{}, fmt.Errorf("build readiness tls config for %s: %w", upstreamCfg.Name, err)
}
tr := defaultHTTPTransport()
tr.TLSClientConfig = tlsCfg
hostTransports[host] = tr
}

upstreams[i] = health.Upstream{
Name: upstreamCfg.Name,
BaseURL: upstreamCfg.BaseURL,
HealthPath: upstreamCfg.HealthPath,
}
}

httpClient := &http.Client{
Timeout: readinessTimeout,
Transport: &upstreamTransport{
defaultTransport: defaultTransport,
transports: hostTransports,
},
}

checker := health.NewChecker(httpClient, upstreams, readinessTimeout, cfg.Readiness.UserAgent)

var registry *gatewaymetrics.Registry
if cfg.Metrics.Enabled {
registry = gatewaymetrics.NewRegistry()
}

if logger == nil {
logger = pkglog.Shared()
}

srv := gatewayserver.New(cfg, checker, registry, gatewayserver.WithLogger(logger))
return struct {
server *gatewayserver.Server
checker *health.Checker
registry *gatewaymetrics.Registry
}{server: srv, checker: checker, registry: registry}, nil
}

Walkthrough

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

  • L253: readinessTimeout := cfg.Readiness.Timeout.AsDuration()
    • What: Defines readinessTimeout.
    • 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.
  • L254: defaultTransport := defaultHTTPTransport()
    • What: Defines defaultTransport.
    • 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.
  • L255: hostTransports := make(map[string]*http.Transport)
    • What: Defines hostTransports.
    • 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.
  • L257: upstreams := make([]health.Upstream, len(cfg.Readiness.Upstreams))
    • What: Defines 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.
  • L258: for i, upstreamCfg := range cfg.Readiness.Upstreams { host, err := hostFromURL(upstreamCfg.BaseURL) if err != nil { return struct { server …
    • What: Iterates over a collection.
    • Why: Processes multiple elements with the same logic.
    • How: Executes a for ... range loop.
    • Nested steps:
      • L259: host, err := hostFromURL(upstreamCfg.BaseURL)
        • What: Defines host, 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.
      • L260: if err != nil { return struct { server *gatewayserver.Server checker *health.Checker registry *gatewaymetrics.Registry }{}, fmt.Errorf("par…
        • 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:
          • L261: return struct { server *gatewayserver.Server checker *health.Checker registry *gatewaymetrics.Registry }{}, fmt.Errorf("parse upstream %s b…
            • 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).
      • L267: if upstreamCfg.TLS.Enabled { tlsCfg, err := buildReadinessTLSConfig(upstreamCfg.TLS) if err != nil { return struct { server *gatewayserver.…
        • What: Branches conditionally.
        • Why: Handles different execution paths based on runtime state.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L268: tlsCfg, err := buildReadinessTLSConfig(upstreamCfg.TLS)
            • What: Defines tlsCfg, 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.
          • L269: if err != nil { return struct { server *gatewayserver.Server checker *health.Checker registry *gatewaymetrics.Registry }{}, fmt.Errorf("bui…
            • 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:
              • L270: return struct { server *gatewayserver.Server checker *health.Checker registry *gatewaymetrics.Registry }{}, fmt.Errorf("build readiness tls…
                • 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).
          • L276: tr := defaultHTTPTransport()
            • What: Defines tr.
            • 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.
          • L277: tr.TLSClientConfig = tlsCfg
            • What: Assigns tr.TLSClientConfig.
            • 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.
          • L278: hostTransports[host] = tr
            • What: Assigns hostTransports[host].
            • 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.
      • L281: upstreams[i] = health.Upstream{ Name: upstreamCfg.Name, BaseURL: upstreamCfg.BaseURL, HealthPath: upstreamCfg.HealthPath, }
        • What: Assigns upstreams[i].
        • 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.
  • L288: httpClient := &http.Client{ Timeout: readinessTimeout, Transport: &upstreamTransport{ defaultTransport: defaultTransport, transports: hostT…
    • What: Defines httpClient.
    • 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.
  • L296: checker := health.NewChecker(httpClient, upstreams, readinessTimeout, cfg.Readiness.UserAgent)
    • What: Defines checker.
    • 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: var registry *gatewaymetrics.Registry
    • What: Declares local names.
    • Why: Introduces variables or types used later in the function.
    • How: Executes a Go declaration statement inside the function body.
  • L299: if cfg.Metrics.Enabled { registry = gatewaymetrics.NewRegistry() }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L300: registry = gatewaymetrics.NewRegistry()
        • What: Assigns registry.
        • 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.
  • L303: if logger == nil { logger = pkglog.Shared() }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L304: logger = pkglog.Shared()
        • What: Assigns logger.
        • 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.
  • L307: srv := gatewayserver.New(cfg, checker, registry, gatewayserver.WithLogger(logger))
    • What: Defines srv.
    • 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.
  • L308: return struct { server *gatewayserver.Server checker *health.Checker registry *gatewaymetrics.Registry }{server: srv, checker: checker, reg…
    • 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).

(*upstreamTransport).RoundTrip

What: Selects a per-host transport (when configured) for an outgoing readiness HTTP request.

Why: Allows readiness checks to use custom TLS settings per upstream host while keeping a shared default for others.

How: If the request host matches transports[host], delegates to that transport; otherwise uses defaultTransport.

pkg/gateway/runtime/runtime.go#L320
func (t *upstreamTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if req == nil || req.URL == nil {
return t.defaultTransport.RoundTrip(req)
}
if transport, ok := t.transports[req.URL.Host]; ok {
return transport.RoundTrip(req)
}
return t.defaultTransport.RoundTrip(req)
}

Walkthrough

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

  • L321: if req == nil || req.URL == nil { return t.defaultTransport.RoundTrip(req) }
    • 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:
      • L322: return t.defaultTransport.RoundTrip(req)
        • 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).
  • L324: if transport, ok := t.transports[req.URL.Host]; ok { return transport.RoundTrip(req) }
    • 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:
      • L324: transport, ok := t.transports[req.URL.Host]
        • What: Defines transport, 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.
      • L325: return transport.RoundTrip(req)
        • 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).
  • L327: return t.defaultTransport.RoundTrip(req)
    • 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).

(*upstreamTransport).CloseIdleConnections

What: Closes idle connections for the default transport and all per-host transports.

Why: Prevents leaked keep-alives when swapping/reloading readiness transports.

How: Calls CloseIdleConnections on the default transport and iterates through the map.

pkg/gateway/runtime/runtime.go#L330
func (t *upstreamTransport) CloseIdleConnections() {
if t.defaultTransport != nil {
t.defaultTransport.CloseIdleConnections()
}
for _, transport := range t.transports {
transport.CloseIdleConnections()
}
}

Walkthrough

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

  • L331: if t.defaultTransport != nil { t.defaultTransport.CloseIdleConnections() }
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L332: t.defaultTransport.CloseIdleConnections()
        • What: Calls t.defaultTransport.CloseIdleConnections.
        • Why: Performs side effects or delegates work to a helper.
        • How: Executes the expression statement.
  • L334: for _, transport := range t.transports { transport.CloseIdleConnections() }
    • What: Iterates over a collection.
    • Why: Processes multiple elements with the same logic.
    • How: Executes a for ... range loop.
    • Nested steps:
      • L335: transport.CloseIdleConnections()
        • What: Calls transport.CloseIdleConnections.
        • Why: Performs side effects or delegates work to a helper.
        • How: Executes the expression statement.

defaultHTTPTransport

What: Returns a clone of http.DefaultTransport when possible, otherwise a new http.Transport.

Why: Cloning preserves sane defaults (proxy, keep-alives, dialer settings) while allowing per-upstream TLS customization without mutating global state.

How: Type-asserts http.DefaultTransport to *http.Transport and calls Clone().

pkg/gateway/runtime/runtime.go#L339
func defaultHTTPTransport() *http.Transport {
if base, ok := http.DefaultTransport.(*http.Transport); ok && base != nil {
return base.Clone()
}
return &http.Transport{}
}

Walkthrough

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

  • L340: if base, ok := http.DefaultTransport.(*http.Transport); ok && base != nil { return base.Clone() }
    • 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:
      • L340: base, ok := http.DefaultTransport.(*http.Transport)
        • What: Defines base, 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.
      • L341: return base.Clone()
        • 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).
  • L343: return &http.Transport{}
    • 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).

buildReadinessTLSConfig

What: Builds a tls.Config for readiness probing based on gatewayconfig.TLSConfig.

Why: Readiness probes may need custom CA bundles or client certificates (mTLS) depending on upstream requirements.

How: Sets safe defaults (TLS 1.2+, h2/http1.1), optionally loads a CA bundle, optionally loads a client certificate/key pair, and returns an error for partial mTLS config.

pkg/gateway/runtime/runtime.go#L346
func buildReadinessTLSConfig(cfg gatewayconfig.TLSConfig) (*tls.Config, error) {
tlsCfg := &tls.Config{
MinVersion: tls.VersionTLS12,
InsecureSkipVerify: cfg.InsecureSkipVerify,
NextProtos: []string{"h2", "http/1.1"},
}

if cfg.CAFile != "" {
data, err := os.ReadFile(cfg.CAFile)
if err != nil {
return nil, fmt.Errorf("read ca file %q: %w", cfg.CAFile, err)
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(data) {
return nil, fmt.Errorf("parse ca bundle %q", cfg.CAFile)
}
tlsCfg.RootCAs = pool
}

if cfg.ClientCertFile != "" || cfg.ClientKeyFile != "" {
if cfg.ClientCertFile == "" || cfg.ClientKeyFile == "" {
return nil, errors.New("client certificate and key must both be provided")
}
cert, err := tls.LoadX509KeyPair(cfg.ClientCertFile, cfg.ClientKeyFile)
if err != nil {
return nil, fmt.Errorf("load client key pair: %w", err)
}
tlsCfg.Certificates = []tls.Certificate{cert}
}

return tlsCfg, nil
}

Walkthrough

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

  • L347: tlsCfg := &tls.Config{ MinVersion: tls.VersionTLS12, InsecureSkipVerify: cfg.InsecureSkipVerify, NextProtos: []string{"h2", "http/1.1"}, }
    • What: Defines tlsCfg.
    • 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 cfg.CAFile != "" { data, err := os.ReadFile(cfg.CAFile) if err != nil { return nil, fmt.Errorf("read ca file %q: %w", cfg.CAFile, err) }…
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L354: data, err := os.ReadFile(cfg.CAFile)
        • 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.
      • L355: if err != nil { return nil, fmt.Errorf("read ca file %q: %w", cfg.CAFile, 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 nil, fmt.Errorf("read ca file %q: %w", cfg.CAFile, 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: pool := x509.NewCertPool()
        • What: Defines pool.
        • 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.
      • L359: if !pool.AppendCertsFromPEM(data) { return nil, fmt.Errorf("parse ca bundle %q", cfg.CAFile) }
        • 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:
          • L360: return nil, fmt.Errorf("parse ca bundle %q", cfg.CAFile)
            • 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).
      • L362: tlsCfg.RootCAs = pool
        • What: Assigns tlsCfg.RootCAs.
        • 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.
  • L365: if cfg.ClientCertFile != "" || cfg.ClientKeyFile != "" { if cfg.ClientCertFile == "" || cfg.ClientKeyFile == "" { return nil, errors.New("c…
    • What: Branches conditionally.
    • Why: Handles different execution paths based on runtime state.
    • How: Evaluates the condition and executes the matching branch.
    • Nested steps:
      • L366: if cfg.ClientCertFile == "" || cfg.ClientKeyFile == "" { return nil, errors.New("client certificate and key must both be provided") }
        • 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:
          • L367: return nil, errors.New("client certificate and key must both be provided")
            • 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).
      • L369: cert, err := tls.LoadX509KeyPair(cfg.ClientCertFile, cfg.ClientKeyFile)
        • What: Defines cert, 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.
      • L370: if err != nil { return nil, fmt.Errorf("load client key pair: %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:
          • L371: return nil, fmt.Errorf("load client key pair: %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).
      • L373: tlsCfg.Certificates = []tls.Certificate{cert}
        • What: Assigns tlsCfg.Certificates.
        • 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.
  • L376: return tlsCfg, 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).

hostFromURL

What: Extracts the Host portion from a base URL string.

Why: Readiness uses host-specific transports for TLS settings; the host is the stable key for transport selection.

How: Parses the URL and returns parsed.Host, returning an error for empty/invalid URLs.

pkg/gateway/runtime/runtime.go#L379
func hostFromURL(raw string) (string, error) {
if strings.TrimSpace(raw) == "" {
return "", fmt.Errorf("empty url")
}
parsed, err := url.Parse(raw)
if err != nil {
return "", err
}
if parsed.Host == "" {
return "", fmt.Errorf("url %q missing host", raw)
}
return parsed.Host, nil
}

Walkthrough

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

  • L380: if strings.TrimSpace(raw) == "" { return "", fmt.Errorf("empty url") }
    • 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:
      • L381: return "", fmt.Errorf("empty url")
        • 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).
  • L383: parsed, err := url.Parse(raw)
    • 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.
  • L384: if err != nil { return "", 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:
      • L385: return "", 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).
  • L387: if parsed.Host == "" { return "", fmt.Errorf("url %q missing host", raw) }
    • 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:
      • L388: return "", fmt.Errorf("url %q missing host", raw)
        • 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).
  • L390: return parsed.Host, 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).

parseAllowList

What: Parses admin.allow entries into CIDRs (*net.IPNet) for IP-based admin authorization.

Why: When no admin token is configured, access is restricted to loopback or explicitly allowed networks.

How: Accepts CIDR strings (via net.ParseCIDR) and single IPs (converted to /32 or /128).

pkg/gateway/runtime/runtime.go#L393
func parseAllowList(entries []string) []*net.IPNet {
if len(entries) == 0 {
return nil
}
allow := make([]*net.IPNet, 0, len(entries))
for _, entry := range entries {
e := strings.TrimSpace(entry)
if e == "" {
continue
}
if strings.Contains(e, "/") {
if _, network, err := net.ParseCIDR(e); err == nil {
allow = append(allow, network)
}
continue
}
if ip := net.ParseIP(e); ip != nil {
mask := net.CIDRMask(len(ip)*8, len(ip)*8)
allow = append(allow, &net.IPNet{IP: ip, Mask: mask})
}
}
return allow
}

Walkthrough

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

  • L394: if len(entries) == 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:
      • L395: 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).
  • L397: allow := make([]*net.IPNet, 0, len(entries))
    • What: Defines 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.
  • L398: for _, entry := range entries { e := strings.TrimSpace(entry) if e == "" { continue } if strings.Contains(e, "/") { if _, network, err := n…
    • What: Iterates over a collection.
    • Why: Processes multiple elements with the same logic.
    • How: Executes a for ... range loop.
    • Nested steps:
      • L399: 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.
      • L400: 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:
          • L401: continue
            • What: Executes a statement.
            • Why: Advances the function logic.
            • How: Runs this statement as part of the function body.
      • L403: if strings.Contains(e, "/") { if _, network, err := net.ParseCIDR(e); err == nil { allow = append(allow, network) } continue }
        • What: Branches conditionally.
        • Why: Handles different execution paths based on runtime state.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L404: if _, network, err := net.ParseCIDR(e); err == nil { allow = append(allow, network) }
            • What: Branches conditionally.
            • Why: Handles different execution paths based on runtime state.
            • How: Evaluates the condition and executes the matching branch.
            • Nested steps:
              • L404: _, network, err := net.ParseCIDR(e)
                • What: Defines _, network, 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.
              • L405: allow = append(allow, network)
                • What: Assigns 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.
          • L407: continue
            • What: Executes a statement.
            • Why: Advances the function logic.
            • How: Runs this statement as part of the function body.
      • L409: if ip := net.ParseIP(e); ip != nil { mask := net.CIDRMask(len(ip)*8, len(ip)*8) allow = append(allow, &net.IPNet{IP: ip, Mask: mask}) }
        • What: Branches conditionally.
        • Why: Handles different execution paths based on runtime state.
        • How: Evaluates the condition and executes the matching branch.
        • Nested steps:
          • L409: ip := net.ParseIP(e)
            • What: Defines ip.
            • 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: mask := net.CIDRMask(len(ip)*8, len(ip)*8)
            • What: Defines mask.
            • 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: allow = append(allow, &net.IPNet{IP: ip, Mask: mask})
            • What: Assigns 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.
  • L414: return allow
    • 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).

(*Runtime).startAdminServer

What: Starts the admin HTTP server on cfg.Admin.Listen.

Why: Keeps control-plane endpoints separate and optionally enabled.

How: Listens on TCP, registers status/config/reload handlers under /_ _admin/*, runs http.Server.Serve in a goroutine, and shuts down on context cancellation.

pkg/gateway/runtime/runtime.go#L417
func (r *Runtime) startAdminServer(ctx context.Context) error {
ln, err := net.Listen("tcp", r.cfg.Admin.Listen)
if err != nil {
return err
}

r.adminAddr = ln.Addr().String()
mux := http.NewServeMux()
mux.HandleFunc("/__admin/status", r.adminAuth(r.handleAdminStatus))
mux.HandleFunc("/__admin/config", r.adminAuth(r.handleAdminConfig))
mux.HandleFunc("/__admin/reload", r.adminAuth(r.handleAdminReload))

srv := &http.Server{Handler: mux}
r.adminSrv = srv
r.adminErrCh = make(chan error, 1)

go func() {
if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) {
r.adminErrCh <- err
}
close(r.adminErrCh)
}()

go func() {
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), r.cfg.HTTP.ShutdownTimeout.AsDuration())
defer cancel()
_ = srv.Shutdown(shutdownCtx)
}()

return nil
}

Walkthrough

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

  • L418: ln, err := net.Listen("tcp", r.cfg.Admin.Listen)
    • What: Defines ln, 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.
  • L419: if err != nil { return 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: return 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).
  • L423: r.adminAddr = ln.Addr().String()
    • What: Assigns r.adminAddr.
    • 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.
  • L424: mux := http.NewServeMux()
    • What: Defines mux.
    • 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: mux.HandleFunc("/__admin/status", r.adminAuth(r.handleAdminStatus))
    • What: Calls mux.HandleFunc.
    • Why: Performs side effects or delegates work to a helper.
    • How: Executes the expression statement.
  • L426: mux.HandleFunc("/__admin/config", r.adminAuth(r.handleAdminConfig))
    • What: Calls mux.HandleFunc.
    • Why: Performs side effects or delegates work to a helper.
    • How: Executes the expression statement.
  • L427: mux.HandleFunc("/__admin/reload", r.adminAuth(r.handleAdminReload))
    • What: Calls mux.HandleFunc.
    • Why: Performs side effects or delegates work to a helper.
    • How: Executes the expression statement.
  • L429: srv := &http.Server{Handler: mux}
    • What: Defines srv.
    • 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.
  • L430: r.adminSrv = srv
    • What: Assigns r.adminSrv.
    • 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.
  • L431: r.adminErrCh = make(chan error, 1)
    • What: Assigns r.adminErrCh.
    • 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: go func() { if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) { r.adminErrCh <- err } close(r.adminErrCh) }()
    • What: Starts a goroutine.
    • Why: Runs work concurrently.
    • How: Invokes the function call asynchronously using go.
    • Nested steps:
      • L433: func() { if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) { r.adminErrCh <- err } close(r.adminErrCh) }
        • 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:
          • L434: if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) { r.adminErrCh <- err }
            • What: Branches conditionally.
            • Why: Handles different execution paths based on runtime state.
            • How: Evaluates the condition and executes the matching branch.
            • Nested steps:
              • L434: err := srv.Serve(ln)
                • 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.
              • L435: r.adminErrCh <- err
                • What: Sends a value on a channel.
                • Why: Communicates with another goroutine.
                • How: Executes a channel send operation.
          • L437: close(r.adminErrCh)
            • What: Calls close.
            • Why: Performs side effects or delegates work to a helper.
            • How: Executes the expression statement.
  • L440: go func() { <-ctx.Done() shutdownCtx, cancel := context.WithTimeout(context.Background(), r.cfg.HTTP.ShutdownTimeout.AsDuration()) defer ca…
    • What: Starts a goroutine.
    • Why: Runs work concurrently.
    • How: Invokes the function call asynchronously using go.
    • Nested steps:
      • L440: func() { <-ctx.Done() shutdownCtx, cancel := context.WithTimeout(context.Background(), r.cfg.HTTP.ShutdownTimeout.AsDuration()) defer cance…
        • 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:
          • L441: <-ctx.Done()
            • What: Evaluates an expression.
            • Why: Performs side effects or delegates work to a helper.
            • How: Executes the expression statement.
          • L442: shutdownCtx, cancel := context.WithTimeout(context.Background(), r.cfg.HTTP.ShutdownTimeout.AsDuration())
            • What: Defines shutdownCtx, cancel.
            • 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.
          • L443: defer cancel()
            • What: Defers a call for cleanup.
            • Why: Ensures the deferred action runs even on early returns.
            • How: Schedules the call to run when the surrounding function returns.
          • L444: _ = srv.Shutdown(shutdownCtx)
            • What: Assigns _.
            • 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.
  • L447: 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).

(*Runtime).adminAuth

What: Wraps an admin handler with authorization checks.

Why: Keeps the three admin endpoints consistent and avoids repetitive auth boilerplate.

How: Calls authorizeAdmin and invokes the handler only if authorized.

pkg/gateway/runtime/runtime.go#L450
func (r *Runtime) adminAuth(handler func(http.ResponseWriter, *http.Request)) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
if !r.authorizeAdmin(w, req) {
return
}
handler(w, req)
}
}

Walkthrough

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

  • L451: return func(w http.ResponseWriter, req *http.Request) { if !r.authorizeAdmin(w, req) { return } handler(w, req) }
    • 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:
      • L451: func(w http.ResponseWriter, req *http.Request) { if !r.authorizeAdmin(w, req) { return } handler(w, req) }
        • 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:
          • L452: if !r.authorizeAdmin(w, req) { 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:
              • L453: 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).
          • L455: handler(w, req)
            • What: Calls handler.
            • Why: Performs side effects or delegates work to a helper.
            • How: Executes the expression statement.

(*Runtime).authorizeAdmin

What: Implements admin authorization based on either bearer token or IP allowlist.

Why: Admin endpoints can mutate/report runtime state and must be protected.

How: If admin.token is set, requires an Authorization header with a Bearer token matching the configured token; otherwise allows loopback or entries in admin.allow.

pkg/gateway/runtime/runtime.go#L459
func (r *Runtime) authorizeAdmin(w http.ResponseWriter, req *http.Request) bool {
token := strings.TrimSpace(r.cfg.Admin.Token)
if token != "" {
authz := req.Header.Get("Authorization")
if !strings.HasPrefix(authz, "Bearer ") || strings.TrimSpace(authz[7:]) != token {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return false
}
return true
}

host, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
return false
}
ip := net.ParseIP(host)
if ip == nil {
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
return false
}
if ip.IsLoopback() {
return true
}
for _, network := range r.adminAllow {
if network.Contains(ip) {
return true
}
}
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
return false
}

Walkthrough

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

  • L460: token := strings.TrimSpace(r.cfg.Admin.Token)
    • What: Defines 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.
  • L461: if token != "" { authz := req.Header.Get("Authorization") if !strings.HasPrefix(authz, "Bearer ") || strings.TrimSpace(authz[7:]) != token …
    • 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:
      • L462: authz := req.Header.Get("Authorization")
        • What: Defines authz.
        • 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.
      • L463: if !strings.HasPrefix(authz, "Bearer ") || strings.TrimSpace(authz[7:]) != token { http.Error(w, http.StatusText(http.StatusUnauthorized), …
        • 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:
          • L464: http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
            • What: Calls http.Error.
            • Why: Performs side effects or delegates work to a helper.
            • How: Executes the expression statement.
          • L465: return false
            • 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).
      • L467: return true
        • 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: host, _, err := net.SplitHostPort(req.RemoteAddr)
    • What: Defines host, _, 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.
  • L471: if err != nil { http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden) return false }
    • 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:
      • L472: http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
        • What: Calls http.Error.
        • Why: Performs side effects or delegates work to a helper.
        • How: Executes the expression statement.
      • L473: return false
        • 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).
  • L475: ip := net.ParseIP(host)
    • What: Defines ip.
    • 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 ip == nil { http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden) return false }
    • 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:
      • L477: http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
        • What: Calls http.Error.
        • Why: Performs side effects or delegates work to a helper.
        • How: Executes the expression statement.
      • L478: return false
        • 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).
  • L480: if ip.IsLoopback() { return true }
    • 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:
      • L481: return true
        • 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).
  • L483: for _, network := range r.adminAllow { if network.Contains(ip) { return true } }
    • What: Iterates over a collection.
    • Why: Processes multiple elements with the same logic.
    • How: Executes a for ... range loop.
    • Nested steps:
      • L484: if network.Contains(ip) { return true }
        • 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:
          • L485: return true
            • 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).
  • L488: http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
    • What: Calls http.Error.
    • Why: Performs side effects or delegates work to a helper.
    • How: Executes the expression statement.
  • L489: return false
    • 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).

(*Runtime).handleAdminStatus

What: Admin handler that returns runtime status as JSON.

Why: Provides a minimal control-plane "am I alive/what version/what admin address" endpoint.

How: Reports PID, uptime seconds, build version, and admin listen information.

pkg/gateway/runtime/runtime.go#L492
func (r *Runtime) handleAdminStatus(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
r.mu.Lock()
response := map[string]any{
"pid": os.Getpid(),
"uptimeSeconds": time.Since(r.bootTime).Seconds(),
"version": r.cfg.Version,
"admin": map[string]any{
"enabled": r.cfg.Admin.Enabled,
"listen": r.adminAddr,
},
}
r.mu.Unlock()
_ = json.NewEncoder(w).Encode(response)
}

Walkthrough

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

  • L493: w.Header().Set("Content-Type", "application/json")
    • What: Calls w.Header().Set.
    • Why: Performs side effects or delegates work to a helper.
    • How: Executes the expression statement.
  • L494: r.mu.Lock()
    • What: Calls r.mu.Lock.
    • Why: Performs side effects or delegates work to a helper.
    • How: Executes the expression statement.
  • L495: response := map[string]any{ "pid": os.Getpid(), "uptimeSeconds": time.Since(r.bootTime).Seconds(), "version": r.cfg.Version, "admin": map[s…
    • What: Defines response.
    • 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.
  • L504: r.mu.Unlock()
    • What: Calls r.mu.Unlock.
    • Why: Performs side effects or delegates work to a helper.
    • How: Executes the expression statement.
  • L505: _ = json.NewEncoder(w).Encode(response)
    • What: Assigns _.
    • 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.

(*Runtime).handleAdminConfig

What: Admin handler that returns the current config as JSON with secrets redacted.

Why: Enables debugging the running configuration without leaking secrets.

How: Copies the config, clears auth.secret and admin.token, and JSON-encodes the result.

pkg/gateway/runtime/runtime.go#L508
func (r *Runtime) handleAdminConfig(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
cfg := r.Config()
cfg.Auth.Secret = ""
cfg.Admin.Token = ""
_ = json.NewEncoder(w).Encode(cfg)
}

Walkthrough

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

  • L509: w.Header().Set("Content-Type", "application/json")
    • What: Calls w.Header().Set.
    • Why: Performs side effects or delegates work to a helper.
    • How: Executes the expression statement.
  • L510: cfg := r.Config()
    • 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.
  • L511: cfg.Auth.Secret = ""
    • 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.
  • L512: cfg.Admin.Token = ""
    • 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.
  • L513: _ = json.NewEncoder(w).Encode(cfg)
    • What: Assigns _.
    • 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.

(*Runtime).handleAdminReload

What: Admin handler that requests a reload via the caller-provided reload callback.

Why: The runtime doesn't know how to reload configuration sources; this endpoint triggers the caller's policy (watcher, SIGHUP, etc.).

How: Requires POST, ensures reloadFn exists, invokes it, and returns a JSON "accepted" response or an error.

pkg/gateway/runtime/runtime.go#L516
func (r *Runtime) handleAdminReload(w http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
if r.reloadFn == nil {
http.Error(w, "runtime reload callback not configured", http.StatusServiceUnavailable)
return
}
if _, err := r.reloadFn(); err != nil {
http.Error(w, fmt.Sprintf("reload failed: %v", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusAccepted)
_ = json.NewEncoder(w).Encode(map[string]any{"status": "reload requested"})
}

Walkthrough

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

  • L517: if req.Method != http.MethodPost { http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) 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:
      • L518: http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
        • What: Calls http.Error.
        • Why: Performs side effects or delegates work to a helper.
        • How: Executes the expression statement.
      • L519: 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).
  • L521: if r.reloadFn == nil { http.Error(w, "runtime reload callback not configured", http.StatusServiceUnavailable) 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:
      • L522: http.Error(w, "runtime reload callback not configured", http.StatusServiceUnavailable)
        • What: Calls http.Error.
        • Why: Performs side effects or delegates work to a helper.
        • How: Executes the expression statement.
      • L523: 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).
  • L525: if _, err := r.reloadFn(); err != nil { http.Error(w, fmt.Sprintf("reload failed: %v", err), http.StatusInternalServerError) 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:
      • L525: _, err := r.reloadFn()
        • 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.
      • L526: http.Error(w, fmt.Sprintf("reload failed: %v", err), http.StatusInternalServerError)
        • What: Calls http.Error.
        • Why: Performs side effects or delegates work to a helper.
        • How: Executes the expression statement.
      • L527: 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).
  • L529: w.Header().Set("Content-Type", "application/json")
    • What: Calls w.Header().Set.
    • Why: Performs side effects or delegates work to a helper.
    • How: Executes the expression statement.
  • L530: w.WriteHeader(http.StatusAccepted)
    • What: Calls w.WriteHeader.
    • Why: Performs side effects or delegates work to a helper.
    • How: Executes the expression statement.
  • L531: _ = json.NewEncoder(w).Encode(map[string]any{"status": "reload requested"})
    • What: Assigns _.
    • 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.

(*Runtime).AdminAddr

What: Returns the bound admin server address (host:port) when enabled.

Why: Helpful when the admin listener is configured with an ephemeral port or needs to be surfaced to callers/tests.

How: Returns Runtime.adminAddr guarded by the runtime mutex.

pkg/gateway/runtime/runtime.go#L535
func (r *Runtime) AdminAddr() string {
r.mu.Lock()
defer r.mu.Unlock()
return r.adminAddr
}

Walkthrough

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

  • L536: r.mu.Lock()
    • What: Calls r.mu.Lock.
    • Why: Performs side effects or delegates work to a helper.
    • How: Executes the expression statement.
  • L537: defer r.mu.Unlock()
    • What: Defers a call for cleanup.
    • Why: Ensures the deferred action runs even on early returns.
    • How: Schedules the call to run when the surrounding function returns.
  • L538: return r.adminAddr
    • 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