Skip to main content

Crate rust_web_server

Crate rust_web_server 

Source
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.json and talk to it with SendMessage, GetTask, ListTasks, CancelTask.
acmeacme
adminNon-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.toml and 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_statehttp2
Async-capable state-aware application — requires the http2 feature (tokio).
authauth
Built-in authentication middleware (auth Cargo 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.
canaryNon-WebAssembly
Weighted canary / A-B traffic splitting middleware.
circuit_breakerNon-WebAssembly
Circuit breaker state machine and retry middleware.
client_hint
clusterNon-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: validate rws.config.toml without starting the server — the counterpart of nginx -t / caddy validate.
config_reload
Hot configuration reload.
config_watchNon-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 the New trait (a constructor used across the crate, much like Default).
cors
cryptocrypto
Password hashing and secure token generation.
csrfcsrf
CSRF protection middleware using the double-submit cookie pattern.
ctlNon-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_mcpNon-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 and rws.app.toml (crate::app_manifest), the last requests and errors, and with a model-* 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. Below RWS_CONFIG_MIN_FREE_DISK free 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): Link headers a client can act on — preload a stylesheet, preconnect to an origin — while the response is still being made.
entry_point
error
ext
extract
fastcgiNon-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.
fleethttp2 and 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_apigateway-api
A Kubernetes Gateway API controller (gateway-api feature, 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 in spec/GATEWAY_API.md.
handler
Typed handlers (18.28.0, #86): extractors as function arguments, any IntoResponse as 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.
ingressNon-WebAssembly
Kubernetes Ingress watcher and router.
ip_filter
IP address allowlist and denylist middleware.
jobsjobs
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
llmNon-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.
logNon-WebAssembly
macros
Declarative routing macro.
mailermailer and 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
modelmodel-mysql or model-postgres or model-sqlite
Model — Async Database Access Layer
null
Null: a value representing JSON null, with FromStr (failing with ParseNullError), Display, Clone, Debug, PartialEq and New.
openapiopenapi
OpenAPI 3.1 documents generated from registered routes, with request and response schemas from serde types.
otelNon-WebAssembly
OpenTelemetry-compatible distributed tracing.
pagination
Pagination result types (Page<T>, CursorPage<T>) and an RFC 8288 Link header builder.
prelude
Convenience re-exports for writing handlers and running the server.
proxyNon-WebAssembly
Reverse proxy middleware with round-robin load balancing.
proxy_configNon-WebAssembly
Config-driven proxy application.
range
Byte ranges (RFC 9110 §14) and response bodies.
rate_limit
request
HTTP requests: Request and 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_keyauth-asymmetric or sso
RSA public keys and RS256 / rsa-sha256 signature verification (no rsa crate). RSA public keys and RS256 / rsa-sha256 signature verification (no rsa crate). RSA public keys and RSASSA-PKCS1-v1_5 / SHA-256 signature verification — everything rws does with RSA (RS256 JWTs, SAML rsa-sha256 signatures), 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.
secretssecrets
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/sso modules.
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).
ssosso
OAuth 2.0 / OIDC SSO client support.
state
Shared application state and state-aware routing.
storagestorage-azure or storage-gcs or storage-local or storage-s3
File / object storage abstraction.
symbol
systemdUnix and (http1 or http2)
systemd integration (18.20.0, #67), without libsystemd.
tcp_proxyNon-WebAssembly
Layer-4 TCP proxy.
templatetera
Tera HTML template engine integration.
test_client
thread_poolNon-WebAssembly
timeoutNon-WebAssembly
Per-route request timeouts.
towertower
Tower interoperability (tower feature): adapters between rws’s own Application/Middleware and the Tower Service/Layer traits, 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_proxyNon-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_target gives 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_pluginwasm-plugins
WebAssembly middleware (18.10.0, #40, feature wasm-plugins): a WasmLayer runs 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.
webhookwebhook
Webhook signature verification for common providers, gated behind the webhook Cargo feature (hmac + sha2 — the same RustCrypto crates already used by crate::auth and crate::crypto).
websocketNon-WebAssembly
WebSocket protocol support — RFC 6455.
ws_proxyNon-WebAssembly
WebSocket reverse proxy.

Macros§

routes
Build a routing app from a declarative table.

Constants§

FIPS
Whether this build uses the FIPS module (fips feature).

Functions§

crypto_provider(http-client or http2) and non-WebAssembly
The rustls crypto provider every TLS config uses: aws-lc-rs, or with the fips feature its FIPS 140-3 validated module and only the algorithms FIPS approves (18.23.0).

Attribute Macros§

deletemacros
Shorthand for #[route(DELETE, "/path")].
getmacros
Shorthand for #[route(GET, "/path")].
patchmacros
Shorthand for #[route(PATCH, "/path")].
postmacros
Shorthand for #[route(POST, "/path")].
putmacros
Shorthand for #[route(PUT, "/path")].
routemacros
Annotate a handler function with its HTTP method and path.

Derive Macros§

Configmacros
Derive load() -> Result<Self, String> for a configuration struct.
FromPathmacros
Derive rust_web_server::handler::FromPath for a struct with named fields: one route parameter per field, by name, each parsed with FromStr. A typed handler’s route must have exactly these parameters (checked at compile time).
FromRequestmacros
Derive FromRequest for a named-field struct.
JsonSchemamacros
Derive rust_web_server::schema::JsonSchema for a struct with named fields or an enum of unit variants.
Modelmacros and (model-mysql or model-postgres or model-sqlite)
Derive rust_web_server::model::Model for a struct.
Validatemacros
Derive Validate for a named-field struct.