Expand description
§rust-web-server
An HTTP/1.1, HTTP/2, and HTTP/3 (QUIC) server, reverse proxy, and
application framework in one crate. HTTP/1.1 parsing, routing, middleware,
JSON, WebSocket, and SSE are implemented in-crate; HTTP/2 and HTTP/3
framing use the h2 and quinn/h3 crates, and TLS uses rustls.
§Use as a library
Add to Cargo.toml:
[dependencies]
rust-web-server = "18"§Quick start
use rust_web_server::prelude::*;
fn hello(_: &Request, _: &PathParams, _: &ConnectionInfo, _: &()) -> Response {
Response::text(STATUS_CODE_REASON_PHRASE.n200_ok, "Hello, world!")
}
fn main() {
let app = App::with_state(()).get("/hello", hello);
let (listener, pool) = Server::setup().unwrap();
Server::run(listener, pool, app);
}See DEVELOPER.md for the full building blocks reference and use case examples.
§Features
On docs.rs every item is shown, labelled with the features it needs. The
presets web, api, proxy and full turn on common sets; see
Feature flags.
Modules§
- a2a
- A2A (Agent2Agent) 1.0 server, JSON-RPC binding (18.17.0, #65): other
agents discover this one by its Agent Card at
/.well-known/agent-card.jsonand talk to it withSendMessage,GetTask,ListTasks,CancelTask. - acme
acme - admin
Non-WebAssembly - The admin API (18.10.0, #29): change and inspect a running server on a listener of its own, never on the public routes.
- app
- app_
manifest rws.app.tomland the conventional app layout (18.28.0).rws.app.toml: the app manifest, and the conventional layout of an rws application (18.28.0, roadmap #87).- application
- Application: the type a server runs for every request.
- async_
state http2 - Async-capable state-aware application — requires the
http2feature (tokio). - auth
auth - Built-in authentication middleware (
authCargo feature). - authz
- Authorization (18.14.0, #32): who the caller is (
Identity), and — from later tranches — what they may do, as relationship-based access control (Zanzibar-style tuples and a schema). - blocklist
- Runtime IP blocklist middleware.
- body
- Request and response bodies.
- cache
- In-memory response cache middleware.
- canary
Non-WebAssembly - Weighted canary / A-B traffic splitting middleware.
- circuit_
breaker Non-WebAssembly - Circuit breaker state machine and retry middleware.
- client_
hint - cluster
Non-WebAssembly - Runtime state shared across replicas through Redis (18.22.0). Runtime state shared across replicas through Redis (18.22.0). Runtime state shared across replicas (18.22.0, #76).
- compression
- config_
binding - Typed configuration binding — read environment variables into strongly-typed structs.
- config_
check rws --check: validaterws.config.tomlwithout starting the server — the counterpart ofnginx -t/caddy validate.- config_
reload - Hot configuration reload.
- config_
watch Non-WebAssembly - Reload when the config file or a certificate changes (
watch = true, #10). - controller
- Controllers: one unit of request handling for
App. - cookie
- core
- Small shared utilities:
base64,sha256(SHA-256, HMAC-SHA256) and theNewtrait (a constructor used across the crate, much likeDefault). - cors
- crypto
crypto - Password hashing and secure token generation.
- csrf
csrf - CSRF protection middleware using the double-submit cookie pattern.
- ctl
Non-WebAssembly rws ctl/rwsctl: the admin API from the command line (18.20.0).rws ctl(18.20.0, #70): the admin API from the command line.- dev_mcp
Non-WebAssembly app.dev_mcp(): an MCP endpoint for a coding agent working on the app (18.28.0).app.dev_mcp(): an MCP endpoint for a coding agent (18.28.0).app.dev_mcp(): an MCP endpoint that lets a coding agent look inside the application it is working on — its routes and the middleware around them, its effective configuration (secrets hidden), its layout andrws.app.toml(crate::app_manifest), the last requests and errors, and with amodel-*feature its models, database schema and migrations. Since 18.28.0 (roadmap #85, #87).- di
- Lightweight type-keyed dependency injection container.
- disk_
guard - Keep rws from filling a disk (18.15.0): before writing to a file it
keeps growing — the access log, the disk cache — rws asks
has_room. BelowRWS_CONFIG_MIN_FREE_DISKfree on that file’s filesystem the write is skipped (and counted) until space comes back: a full disk costs log lines and cache entries, never the server or whatever shares the disk with it. - early_
hints 103 Early Hints(RFC 8297, 18.12.0, #38):Linkheaders a client can act on — preload a stylesheet, preconnect to an origin — while the response is still being made.- entry_
point - error
- ext
- extract
- fastcgi
Non-WebAssembly - FastCGI client: PHP through php-fpm (18.21.0). FastCGI client: PHP through php-fpm (18.21.0). FastCGI (18.21.0, #72): PHP through php-fpm, and any other FastCGI responder, without FrankenPHP or a second web server.
- feature
- Runtime feature toggles.
- fleet
http2and non-WebAssembly - Fleet config pull: signed configs from HTTPS, S3 or git (18.23.0). Fleet config pull: signed configs from HTTPS, S3 or git (18.23.0). Fleet config pull (18.23.0, #80): many instances, one source of truth.
- gateway_
api gateway-api - A Kubernetes Gateway API controller (
gateway-apifeature, 18.8.0, #19): rws watches GatewayClasses, Gateways and routes, serves their traffic, and reports what it accepted in their status. The plan and progress are inspec/GATEWAY_API.md. - handler
- Typed handlers (18.28.0, #86): extractors as function arguments, any
IntoResponseas the return value, the route’s method and pattern taken from the#[get]/#[post]/… attribute. - header
- HTTP header fields.
- http
- http_
client - Outbound HTTP/1.1 client.
- i18n
- Translations (18.16.0, #33): message catalogs, one per language, and the language each request asks for.
- ingress
Non-WebAssembly - Kubernetes Ingress watcher and router.
- ip_
filter - IP address allowlist and denylist middleware.
- jobs
jobs - Background job queue for one-shot, fire-and-forget work triggered from request handlers — e.g. “send a confirmation email after signup” — without blocking the response.
- json
- A dependency-free JSON parser and serializer.
- language
- llm
Non-WebAssembly - An LLM proxy (18.9.0, #41): one endpoint in front of OpenAI-compatible and Anthropic providers that counts tokens, enforces budgets and fails over between providers.
- log
Non-WebAssembly - macros
- Declarative routing macro.
- mailer
mailerand non-WebAssembly - Transactional email via SMTP.
- maintenance
- Maintenance mode middleware.
- mcp
- Model Context Protocol (MCP) server — HTTP Streamable HTTP transport.
- metrics
- Server-wide and per-route Prometheus metrics.
- middleware
- Composable middleware pipeline.
- mime_
type - model
model-mysqlormodel-postgresormodel-sqlite - Model — Async Database Access Layer
- null
Null: a value representing JSONnull, withFromStr(failing withParseNullError),Display,Clone,Debug,PartialEqandNew.- openapi
openapi - OpenAPI 3.1 documents generated from registered routes, with request and response schemas from serde types.
- otel
Non-WebAssembly - OpenTelemetry-compatible distributed tracing.
- pagination
- Pagination result types (
Page<T>,CursorPage<T>) and an RFC 8288Linkheader builder. - prelude
- Convenience re-exports for writing handlers and running the server.
- proxy
Non-WebAssembly - Reverse proxy middleware with round-robin load balancing.
- proxy_
config Non-WebAssembly - Config-driven proxy application.
- range
- Byte ranges (RFC 9110 §14) and response bodies.
- rate_
limit - request
- HTTP requests:
Requestand its parser. - request_
id - Request ID / correlation ID middleware.
- request_
log - In-memory ring buffer of recent HTTP requests.
- response
- HTTP responses:
Response, its writers and the upstream-response parser. - rewrite
- Request and response rewriting middleware.
- router
- rsa_key
auth-asymmetricorsso - RSA public keys and RS256 / rsa-sha256 signature verification (no
rsacrate). RSA public keys and RS256 / rsa-sha256 signature verification (norsacrate). RSA public keys and RSASSA-PKCS1-v1_5 / SHA-256 signature verification — everythingrwsdoes with RSA (RS256 JWTs, SAMLrsa-sha256signatures), implemented in-crate. - scheduler
- Background task scheduler — a
@Scheduled-style runner for fixed-rate, fixed-delay, and cron-expression tasks. - schema
- JSON Schema for Rust types, for MCP tool
inputSchema/outputSchema. - secrets
secrets - Secret-reference resolution for HashiCorp Vault, AWS Secrets Manager, and
Azure Key Vault — no vendor SDK for any of the three, matching this
crate’s existing
storage-s3/storage-azure/ssomodules. - server
- The listeners and connection loops.
- server_
config - Typed server configuration.
- service_
discovery - Dynamic backend pool with pluggable discovery sources.
- session
- Server-side session management.
- sse
- Server-Sent Events (SSE).
- sso
sso - OAuth 2.0 / OIDC SSO client support.
- state
- Shared application state and state-aware routing.
- storage
storage-azureorstorage-gcsorstorage-localorstorage-s3 - File / object storage abstraction.
- symbol
- systemd
Unix and ( http1orhttp2) - systemd integration (18.20.0, #67), without libsystemd.
- tcp_
proxy Non-WebAssembly - Layer-4 TCP proxy.
- template
tera - Tera HTML template engine integration.
- test_
client - thread_
pool Non-WebAssembly - timeout
Non-WebAssembly - Per-route request timeouts.
- tower
tower - Tower interoperability (
towerfeature): adapters between rws’s ownApplication/Middlewareand the TowerService/Layertraits, so tonic gRPC services and tower-http layers work in an rws app, and an rws app works in a Tower stack. rws itself doesn’t run on Tower: its request path stays the native one, and nothing here is compiled without the feature. - traffic
- Traffic insights (18.15.0): who visits — people, AI agents, bots — worked out by rws from each request, for the admin UI’s Traffic page.
- udp_
proxy Non-WebAssembly - Layer-4 UDP proxy.
- url
- URL helpers: percent encoding (
URL::percent_encode/percent_decode), query strings (URL::build_query/parse_query) and whole URLs (URL::build/parse, a panic-free RFC 3986 parser).URL::parse_request_targetgives a request’s path and query without inventing a scheme and host. Percent encoding is what lets a query value carry a space (%20),=(%3D) or&(%26). Examples:crates/rws-base/src/url/example/. - validate
- virtual_
host - waf
- Web application firewall: rws’s own rules (18.22.0). Web application firewall: rws’s own rules (18.22.0). Web application firewall (18.22.0, #77): rws’s own rules, no rule language to learn and no external engine.
- wasm_
plugin wasm-plugins - WebAssembly middleware (18.10.0, #40, feature
wasm-plugins): aWasmLayerruns a core WebAssembly module on each request and, optionally, each response. The module may let the request pass, change its headers or target, answer it itself, or change the response’s status and headers. - webhook
webhook - Webhook signature verification for common providers, gated behind the
webhookCargo feature (hmac+sha2— the same RustCrypto crates already used bycrate::authandcrate::crypto). - websocket
Non-WebAssembly - WebSocket protocol support — RFC 6455.
- ws_
proxy Non-WebAssembly - WebSocket reverse proxy.
Macros§
- routes
- Build a routing app from a declarative table.
Constants§
- FIPS
- Whether this build uses the FIPS module (
fipsfeature).
Functions§
- crypto_
provider ( http-clientorhttp2) and non-WebAssembly - The rustls crypto provider every TLS config uses: aws-lc-rs, or with the
fipsfeature its FIPS 140-3 validated module and only the algorithms FIPS approves (18.23.0).
Attribute Macros§
- delete
macros - Shorthand for
#[route(DELETE, "/path")]. - get
macros - Shorthand for
#[route(GET, "/path")]. - patch
macros - Shorthand for
#[route(PATCH, "/path")]. - post
macros - Shorthand for
#[route(POST, "/path")]. - put
macros - Shorthand for
#[route(PUT, "/path")]. - route
macros - Annotate a handler function with its HTTP method and path.
Derive Macros§
- Config
macros - Derive
load() -> Result<Self, String>for a configuration struct. - From
Path macros - Derive
rust_web_server::handler::FromPathfor a struct with named fields: one route parameter per field, by name, each parsed withFromStr. A typed handler’s route must have exactly these parameters (checked at compile time). - From
Request macros - Derive
FromRequestfor a named-field struct. - Json
Schema macros - Derive
rust_web_server::schema::JsonSchemafor a struct with named fields or an enum of unit variants. - Model
macrosand (model-mysqlormodel-postgresormodel-sqlite) - Derive
rust_web_server::model::Modelfor a struct. - Validate
macros - Derive
Validatefor a named-field struct.