rws
An HTTP web framework, reverse proxy, and server for Rust supporting HTTP/1.1, HTTP/2, and HTTP/3. No third-party HTTP dependencies — parsing, routing, middleware, auth, WebSocket, SSE, caching, tracing, and MCP server are all built in.
Use it as a config-driven proxy server (drop an rws.config.toml with [[route]] and [[upstream]] sections — no code required), as a ready-to-run static file server, or pull it in as a library crate to get battle-tested building blocks — request/response parsing, routing, middleware, JSON, sessions, auth, SSE — without taking on a full async framework.
Install
This installs the rws binary with HTTP/3, HTTP/2, and TLS support included.
Run
Plain HTTP/1.1
Starts on http://127.0.0.1:7878 by default. Place your files in the working directory and open the URL in a browser.
HTTPS + HTTP/2 + HTTP/3
Generate a self-signed certificate for local development:
Start the server with the certificate:
Open https://127.0.0.1:7878 in a browser. The server listens on the same port for both TCP (HTTP/1.1 and HTTP/2 via ALPN) and UDP (HTTP/3 via QUIC). HTTP/2 and HTTP/3 are negotiated automatically — no extra configuration needed.
For a public domain, obtain a certificate from Let's Encrypt.
Custom address and port
See CONFIGURE for all configuration options (env vars, config file, command-line flags).
Config-driven proxy server
Drop an rws.config.toml in the working directory with [[route]] and [[upstream]] blocks and rws starts as a full reverse proxy — no code required:
[[]]
= "api"
= ["10.0.0.10:8080", "10.0.0.11:8080"]
[]
= "/healthz"
= 10
= 2000
= 2
= 3
[[]]
= "api-proxy"
[]
= "api.example.com"
= "/v1/*"
[]
= "proxy"
= "api"
[]
= { = 500, = 60 }
= { = "bearer", = "API_TOKEN" }
[[]]
= "catch-all"
[]
= "/*"
[]
= "respond"
= 404
= "Not Found"
See spec/PROXY_SERVER_CONFIG.md for the full annotated config reference.
Build from source
The binary is at target/release/rws.
To build with HTTP/2 only (no QUIC/HTTP/3):
To build HTTP/1.1 only (smallest binary, no TLS):
Features
Server
- HTTP/3 over QUIC (UDP) — negotiated via
Alt-Svc - HTTP/2 with ALPN negotiation alongside HTTP/1.1 on the same TCP port
- TLS via rustls (aws-lc-rs backend, no OpenSSL)
- HTTP/1.1 keep-alive — persistent connections;
Connection: closeor idle timeout ends the session - Response compression — automatic gzip for text types when client sends
Accept-Encoding: gzip - Large file streaming — chunked transfer for files > 8 MB; no full-file buffering
- Virtual hosting / SNI routing — serve multiple domains from one instance, each with its own TLS certificate; per-domain routing via
Router::with_host() - HTTP → HTTPS redirect — set
RWS_CONFIG_HTTP_REDIRECT_PORTto redirect a plain-HTTP port - CORS — allowed for all origins by default, fully configurable
- HTTP Range Requests — partial file serving and multi-range responses
- ETag and 304 Not Modified — conditional requests skip body transfer on cache hit
- Security headers —
Strict-Transport-Security(HTTPS only),Content-Security-Policy(configurable viaRWS_CONFIG_CSP),Referrer-Policy,Permissions-Policy,X-Content-Type-Options,X-Frame-Options - Combined Log Format (CLF) — access log compatible with GoAccess and AWStats; set
RWS_CONFIG_LOG_FORMAT=jsonfor structured JSON logs - Graceful shutdown — Ctrl+C and SIGTERM drain in-flight connections on all server paths;
/readyzreturns503during drain - Kubernetes-ready — health probes (
GET /healthzliveness,GET /readyzreadiness), Prometheus metrics (GET /metrics),0.0.0.0default bind, Dockerfile included - 30-second read timeout per request on plain HTTP/1.1 connections
- Symlink resolution;
.htmlextension inference; custom404.htmlpage
Library
- Dynamic routing —
Routerwith:paramand*wildcardpath matching;routes!macro builds routing tables declaratively - Shared application state —
App::with_state(S)sharesArc<S>across route handlers - Async handlers —
App::with_async_state(S)gives handlers anasync fnsignature (http2feature, tokio-backed) - Middleware pipeline —
App::new().wrap(layer)stacks composableMiddlewarelayers - Typed errors —
IntoResponsetrait; built-inAppErrorenum covers 400–500 status codes - Typed request extractors —
FromRequesttrait; built-inBody,BodyText,Query,RequestHeaders;#[derive(FromRequest)]generates impls for named-field structs - Request validation —
Validatetrait +Validated<T>wrapper;#[derive(Validate)]with#[validate(length, range, email, required, url)]annotations; returns422with JSON error body - Cookie handling —
CookieJarparses theCookieheader;SetCookiebuilder createsSet-Cookievalues - HTTP Client Hints —
ClientHintextractor reads UA client hint headers - WebSocket support — RFC 6455 handshake, frame encode/decode, SHA-1 + base64 built in, no extra dependency
- Server-Sent Events —
Ssebuilder produces a bufferedtext/event-streamresponse with correct headers - Session management —
SessionStorethread-safe in-memory sessions with TTL; cookie helpers included - Per-IP rate limiting — sliding-window
RateLimiterandRateLimitLayermiddleware; configurable via env vars - Per-route metrics —
MetricsLayermiddleware recordsrws_route_requests_total{method,path,status}counters andrws_route_duration_seconds{method,path}histograms into the global/metricsendpoint; query strings stripped from paths automatically - IP filter —
IpFilter::allow([...])/IpFilter::deny([...])middleware; accepts exact IPv4 addresses and CIDR ranges - Reverse proxy —
ReverseProxymiddleware forwards requests to HTTP backends with round-robin load balancing, automatic failover, andpath_prefixrouting; returns502 Bad Gatewaywhen all backends fail - HTTP/2 reverse proxy —
H2ReverseProxymiddleware forwards requests over HTTP/2 to backends;GrpcProxywraps it to filter onContent-Type: application/grpc*; requireshttp2feature - L4 TCP proxy —
TcpProxystandalone listener relays TCP bytes bidirectionally to round-robin backends; useful for any TCP protocol (databases, legacy services, plain HTTP) - UDP proxy —
UdpProxystandalone datagram proxy; forwards each UDP packet to a backend and returns the reply; suitable for DNS, syslog, and similar request-reply protocols - WebSocket proxy —
WsProxystandalone listener; performs the HTTP upgrade with clients, connects to backends, and relays WebSocket frames bidirectionally in a two-thread relay - mTLS — set
RWS_CONFIG_TLS_CLIENT_CA_FILEto a PEM CA file to require client certificates; verifier built viarustlsWebPkiClientVerifier; applies to both HTTPS and QUIC listeners - Canary / traffic splitting —
CanaryLayermiddleware distributes requests across backends proportionally to configured weights; deterministic, lock-free, zero-dep - Circuit breaker —
CircuitBreakerper-backend state machine (Closed→Open→HalfOpen);global()singleton;RetryLayermiddleware retries on 502/503/504 - Service discovery —
BackendPoolwith four sources:Static,EnvPrefix(env vars),File(polled text file),Dns(A-record lookup); background refresh thread; all clones share one pool - Kubernetes Ingress routing —
KubernetesIngressWatcherpolls the K8s API, parses Ingress rules, andIngressRouterforwards matching requests to cluster services - Background scheduler —
Schedulerwith fixed-rate, fixed-delay, and 6-field cron modes; each task runs in its own thread; full cron syntax (*,*/step,N-M, comma list) - Request / response rewriting —
RewriteLayermiddleware rewrites request headers, URI (set, strip prefix, add prefix), response headers, status code, and response body bytes; composable with any middleware stack - Response caching —
CacheLayermiddleware; in-memory TTL cache for GET responses; vary-by-header for content negotiation; capacity-bounded with oldest-first eviction;Ageheader injected on hits; respectsCache-Control: no-store/private - Hot config reload — send
SIGHUP(orPOST /admin/config/reload) to re-apply CORS rules, rate-limit thresholds, log format, and request allocation size without restarting;config_reload::current()exposes a typed snapshot anywhere in the handler stack - Distributed tracing —
OtelLayermiddleware creates HTTP server spans; reads W3Ctraceparentheaders, propagates context to upstream services, exports to stdout or an OTLP HTTP collector (Jaeger, Grafana Tempo); zero new Cargo dependencies - Automatic TLS —
AcmeManager(acmefeature) provisions and renews Let's Encrypt certificates via ACME (RFC 8555); HTTP-01 challenge server built in; background renewal loop sends SIGHUP so the TLS acceptor hot-reloads the certificate without restarting - MCP server —
McpServerimplementsApplication; exposes tools, resources, and prompts over MCP Streamable HTTP (JSON-RPC 2.0POST /mcp); no extra Cargo features needed; reachable from Claude, Cursor, and other MCP clients; built-in bearer token auth (require_bearer()); the bundled binary ships 8 rws-specific tools (server_config,feature_flags,server_metrics,rate_limit_config,check_rate_limit,cors_config,list_static_files,reload_config) - WebAssembly MIME type —
.wasmfiles served asapplication/wasm - In-process test client —
TestClientdispatches requests without a TCP socket - HTML template engine —
TeraEngine(terafeature) wraps the Tera crate; Jinja2/Django syntax — variables, loops, conditionals, inheritance, filters, macros; global singleton viatemplate::init(dir);template::render(name, &ctx)returns a200 OKHTML response - Typed config binding —
#[derive(Config)](macrosfeature) generatesload() -> Result<Self, String>that reads env vars into strongly-typed structs;#[config(env = "KEY", default = "v")]per field;Option<T>fields are optional;FromEnvStrtrait supports custom types - Config-driven proxy server — drop
rws.config.tomlwith[[route]]/[[upstream]]sections to run as a full reverse proxy with per-route middleware, health-checked backend pools, and L4/WS proxies; no code required - Dependency injection —
Containerstores services keyed byTypeId;register::<T>(val)for concrete types,provide::<dyn Trait>(Arc::new(...))for trait objects, named instances viaregister_named; share withcontainer.into_arc()asApp::with_statestate
Optional features
| Feature | What it adds |
|---|---|
serde |
Json<T> extractor and responder backed by serde_json |
auth |
BasicAuthLayer (HTTP Basic) and JwtLayer (HS256 JWT); build_jwt / verify_jwt utilities |
macros |
#[route], #[get], #[post], #[put], #[patch], #[delete] attributes; #[derive(FromRequest)]; #[derive(Validate)]; #[derive(Config)] (typed env-var binding) via rws-macros |
acme |
AcmeManager — automatic certificate provisioning and renewal via ACME (Let's Encrypt); implies http2 |
tera |
TeraEngine HTML template engine (Jinja2/Django syntax); template::init() global singleton; template::render() one-liner |
[]
= { = "17", = ["serde", "auth", "macros"] }
Use as a library
Add the crate to Cargo.toml:
[]
= "17"
Recommended: declarative routing with routes!
use App;
use New;
use routes;
use Request;
use PathParams;
use ConnectionInfo;
use ;
;
let app = routes! ;
Alternative: Controller trait
For more control — custom matching logic, access to the raw response object, or registering routes in the legacy App::execute chain — implement Controller directly:
use Controller;
use ;
use ;
use Range;
use MimeType;
use ConnectionInfo;
;
See DEVELOPER for the full building blocks reference and 51 use-case examples covering JSON responses, query parameters, form and file upload parsing, redirects, typed errors, typed extractors, rate limiting, testing, WebSocket connections, shared state, middleware, SSE, auth, Serde JSON, sessions, async handlers, IP filtering, declarative routing, request validation, reverse proxy / load balancing, response caching, hot config reload, per-route metrics, distributed tracing, automatic TLS via ACME, MCP server, virtual hosting / SNI routing, request / response rewriting, L4 TCP proxy, UDP proxy, WebSocket proxy, HTTP/2 reverse proxy, gRPC proxy, mTLS, canary routing, circuit breaker, service discovery, Kubernetes Ingress routing, background scheduling, HTML template rendering, and typed configuration binding.
AI adoption
This framework is designed to be an AI first class citizen — AI coding assistants (Claude, Cursor, Copilot) generate correct, idiomatic, compiling code on the first try.
See spec/AI_ADOPTION.md for the full strategy: using the server as an AI API backend, adding SSE streaming for token-by-token output, using the built-in McpServer to expose tools over MCP, and the steps to make the framework maximally discoverable by AI tools (llms.txt, Cargo examples, ergonomic helpers, system prompt file).
Further reading
- CONFIGURE — all configuration options
- FAQ — common problems and solutions
- DEVELOPER — building blocks, use cases, building, and testing
- src/README.md — module-level documentation
- spec/AI_ADOPTION.md — AI adoption strategy and roadmap
License
MIT