Overview
The backend routing system supports flexible request routing based on hostnames and URL paths. It provides both legacy and new configuration formats with round-robin load balancing.Types
Backend
Represents a backend server pool with load balancing.main.go:24-27
List of backend addresses (e.g.,
["web:80", "web2:80"])Atomic counter for round-robin load balancing
HostBackend
Defines routing configuration for a specific host.main.go:42-45
Default backend for requests that don’t match any path prefix
Map of URL path prefixes to specific backends. Longest prefix wins.
Functions
loadBackendsFromEnv()
Loads backend configurations from theBACKENDS environment variable or assigns a default backend.
main.go:98-161
Map of hostnames to their backend configurations
Error if JSON parsing fails
Supported Formats
New Format (Recommended) - Supports path-based routing:Default Behavior
IfBACKENDS is empty or not set:
main.go:100-106
The loader automatically falls back to using the first path backend if no default is specified in the new format (lines 133-140).
pickBackendForRequest()
Selects the appropriate backend for a request based on path prefix matching.main.go:317-341
Host-specific backend configuration
URL path from the request (e.g.,
/static/image.png)Selected backend or nil if none found
Matching Logic
- Longest Prefix Match: Finds the longest matching path prefix from
Pathsmap - Default Fallback: Uses
Defaultbackend if no path matches - Nil Return: Returns nil if no valid backend is configured
Usage Example
From main.go:541-553:splitHostPort()
Extracts the host and port from a network address string. Defaults to port 80 if not specified.main.go:190-199
Network address (e.g.,
"192.168.1.1:8080" or "example.com")Hostname or IP address
Port number (defaults to 80 if not specified)
Usage Example
Load Balancing
Round-Robin Algorithm
Backends with multiple addresses use atomic counter-based round-robin:main.go:552-553
Environment Variables
See Environment Variables for configuration:BACKENDS- JSON configuration for backend routing
Complete Example
example.com/static/logo.png→cdn:80example.com/api/v1/users→api1:8080orapi2:8080(round-robin)example.com/about→web1:80orweb2:80(round-robin)admin.example.com/dashboard→admin:3000unknown.com/page→localhost:5000(default)
