Request routing and middleware
The request path carries an incoming HTTP request from the listener to one configured service and then to an eligible upstream target. Routing selects the service by host and path. Middleware adds request identity, client address information, safety limits, response handling, and final error presentation around that path. See proxy server architecture for the process-level view, services and upstream targets for target state, and upstream load balancing for target selection.
Request lifecycle
The proxy applies shared middleware before dispatch, then service middleware, and finally target middleware around the upstream exchange. The outer chain creates the request context and common limits. The selected target performs the upstream call and returns the result through the response path.
This diagram shows the main path from the client request to the upstream response.
flowchart LR
Client[Incoming request] --> Context[Request identity and start time]
Context --> Timeout[Body read timeout]
Timeout --> Errors[Error response context]
Errors --> Router[Host and path dispatch]
Router --> Service[Service checks and controls]
Service --> Address[Client address handling]
Address --> Target[Target selection]
Target --> RequestBuffer[Optional request buffering]
RequestBuffer --> Upstream[Upstream service]
Upstream --> ResponseBuffer[Optional response buffering]
ResponseBuffer --> Errors
Errors --> Client
The target path is the request path after a matched service prefix is removed. The proxy keeps the original path for routing and uses the target path only when forwarding to an upstream service.
References: internal/…/server.go• L218-229 internal/…/router.go• L136-148 internal/…/service.go• L314-323 internal/…/target.go• L174-184
Router dispatch
The router maps a request to a service by its host and cleaned URL path. A service binding uses a host and a path prefix. The router prefers the longest matching prefix, so a more specific route takes precedence over a broader route.
Host matching supports exact hosts, wildcard parent domains, and the default host binding. The request port does not affect the host match when the host includes a port. A missing service produces a not-found response before service or target processing begins.
Path matching treats a prefix as a path segment. This prevents a route such as /app from matching an unrelated path such as /apple. Path cleaning also keeps a meaningful trailing slash for route matching.
References: internal/…/service_map.go• L81-108 internal/…/service_map.go• L113-165 internal/…/router.go• L136-148
Prefix forwarding
Prefix forwarding controls the URL path seen by the upstream service. When a service enables prefix stripping, the router records the matched prefix in request context. The target then forwards the remaining path and preserves the query string.
The root path is used when the request contains no remaining path after stripping. Services that do not strip the prefix pass the original request path to the upstream service.
References: internal/…/router.go• L27-47 internal/…/router.go• L143-146 internal/…/target.go• L307-341
Request context
Request context carries data across middleware without changing the public HTTP request shape. The proxy uses it for the matched route and for request fields that are collected later by logging and metrics.
The request ID middleware preserves an incoming X-Request-ID value. If the request has no value, it creates one. The request-start middleware follows the same rule for X-Request-Start, which lets an upstream chain retain the first known start time.
The logging middleware creates the shared request record before dispatch. The service and target add their names and rollout information as the request moves inward. When the response returns, the logger records the final status, sizes, duration, address values, and selected headers. See request logging for the logging contract.
References: internal/…/request_id_middleware.go• L16-30 internal/…/request_start_middleware.go• L17-28 internal/…/logging_middleware.go• L45-117 internal/…/service.go• L612-639 internal/…/target.go• L174-180
Client address handling
Client address handling turns a trusted, configured request header into the forwarding and logging address used by the proxy. When the service has a client IP header configured, the proxy copies its value to X-Forwarded-For before the upstream request is sent.
The logger uses X-Forwarded-For when it is present. Otherwise, it uses the network peer address from the connection. This means the configured header must be supplied only by a trusted front proxy; an untrusted value can change the client address seen by the upstream service and in logs.
References: internal/…/client_ip_middleware.go• L7-23 internal/…/logging_middleware.go• L72-101 internal/…/target.go• L344-359
Body protection
Body protection limits slow uploads and oversized requests before they can consume unbounded proxy resources. The body timeout middleware gives each active body read a fresh deadline, so a client that keeps making progress can continue while a stalled client is stopped.
The timeout also covers the HTTP/1 body-drain period after an early response. HTTP/2 and HTTP/3 apply the deadline while a body read is active. A disabled or empty-body request bypasses this protection.
Request buffering reads the full body before the target receives it. It keeps small bodies in memory, spills larger bodies to temporary storage, and rejects bodies above the configured maximum. Buffering makes the body reusable during proxy handling and removes the client read from the upstream exchange.
The main body failures map to client-facing status classes:
| Condition | Result |
|---|---|
| Body exceeds the request limit | 413 Request Entity Too Large |
| Client stalls while sending | 408 Request Timeout |
| Malformed chunked body | 400 Bad Request |
| Other buffering failure | 500 Internal Server Error |
References: internal/…/request_body_timeout_middleware.go• L24-74 internal/…/request_body_timeout_middleware.go• L86-117 internal/…/request_buffer_middleware.go• L23-46 internal/…/buffer.go• L30-43 internal/…/buffer.go• L52-85
Upstream exchange
After service checks pass, the service asks its load balancer to start the request. The selected target records the request as in flight, applies forwarding rules, and sends it through the reverse proxy. Target health, draining, and rollout rules determine whether this step can proceed; see upstream load balancing and services and upstream targets.
The forwarded request keeps the original host and query string. The proxy adds its normal forwarding headers and can carry selected existing forwarding headers when the service allows it. The upstream response then travels back through target and service middleware.
Before the upstream call, a service can redirect a request to its required scheme or canonical host. A paused or stopped service can return a controlled response, while its health checks can still receive success so that downstream systems do not remove it from their pool.
References: internal/…/service.go• L612-665 internal/…/service.go• L668-707 internal/…/target.go• L157-184 internal/…/target.go• L293-341
Response processing
Response processing decides whether the proxy can hold the upstream response before sending it to the client. When enabled for a target, response buffering keeps data in memory up to a limit and then spills to temporary storage. An oversized response is not sent as a partial normal response; it becomes an internal server error.
Streaming responses bypass buffering when they declare server-sent events or chunked transfer encoding. Connection hijacking also bypasses normal buffered delivery. This preserves long-lived and upgraded connections while keeping ordinary responses subject to the size limit.
The error-page middleware renders a status selected by inner handlers. It uses a configured HTML page when one exists and falls back to a plain status response. The root error layer handles failures that no service-specific error layer handled. See proxy error responses for the error classes and client-facing behavior.
References: internal/…/target.go• L121-128 internal/…/response_buffer_middleware.go• L26-44 internal/…/response_buffer_middleware.go• L55-137 internal/…/error_page_middleware.go• L25-65 internal/…/error_page_middleware.go• L70-103
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the router's host and path-prefix rules aligned with prefix removal in
RoutedTargetPathand with the upstream rewrite path. - Keep request body timeout classification aligned between the outer timeout wrapper, request buffering, and the target proxy error handler.
- Keep response buffer bypass rules compatible with the response writer features used by streaming and upgraded connections.
- Keep client IP trust settings aligned between service middleware,
X-Forwarded-Forforwarding, and request log address fields. - Keep error status recording compatible with the error-page middleware so an inner service page does not prevent the root layer from handling an unrendered error.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| No host and path binding matches | The request ends with 404 Not Found and never reaches an upstream target. | Maintain non-conflicting service bindings and verify the host and prefix used by the client. |
| A client stalls while sending a body | The body read fails and the client receives 408 Request Timeout. | Set a body timeout that matches the expected upload behavior. |
| A request or response crosses its configured size limit | The request is rejected or the response becomes 500 Internal Server Error. | Set limits for the largest supported payload and enable buffering only where replay or size control is needed. |
| A service prefix is stripped without preserving the route context | The upstream receives the wrong path. | Treat router prefix matching and target path rewrite as one contract. |
| An untrusted client IP header is accepted | Logs and upstream requests can contain a false client address. | Configure the client IP header only when a trusted proxy controls it. |
| A target is draining when a request starts | The request cannot be assigned and may produce a gateway timeout. | Drain targets through the service and target lifecycle controls. |
Key files
| File | Why to read it |
|---|---|
| internal/…/server.go | Defines the shared middleware order around the router. |
| internal/…/router.go | Shows service dispatch and the route context used for prefix stripping. |
| internal/…/service_map.go | Defines host lookup, path-prefix matching, and route precedence. |
| internal/…/service.go | Shows service-level checks before load balancer dispatch. |
| internal/…/target.go | Defines upstream forwarding, target request tracking, and proxy error classification. |
| internal/…/request_body_timeout_middleware.go | Defines stalled-body protection across HTTP protocol versions. |
| internal/…/request_buffer_middleware.go | Defines request body limits and buffering failures. |
| internal/…/response_buffer_middleware.go | Defines response size control and streaming bypass behavior. |
| internal/…/error_page_middleware.go | Defines the final rendering path for controlled error responses. |
| internal/…/client_ip_middleware.go | Defines configured client address propagation. |
| internal/…/logging_middleware.go | Shows how request context becomes final request records and metrics. |