Expand description
§Churust 🌀
A Ktor-inspired, secure, easy-to-learn web framework for Rust (Churro + Rust).
Churust gives you Ktor’s developer experience on a battle-tested async stack
(tokio + hyper + rustls): an application engine, a routing DSL, an
install(plugin) system, a phased interceptor pipeline, hybrid handlers
(call-style and typed extractors), typed app state, layered configuration,
and secure-by-default behavior (body limits, request timeouts, panic
isolation, opt-in TLS).
This is the umbrella crate: depend on it and enable plugins via Cargo
features. Core types come from churust_core (re-exported here); the
#[churust::main] attribute comes from churust-macros.
§Quick start
use churust::prelude::*;
#[churust::main]
async fn main() -> std::io::Result<()> {
Churust::server()
.routing(|r| {
r.get("/", |_call: Call| async { "Hello from Churust 🌀" });
r.get("/users/{id}", |Path(id): Path<u64>| async move {
format!("user #{id}")
});
})
.start()
.await
}§Testing without a socket
Any app can be driven in-process with TestClient — no port binding, so
tests are fast and deterministic:
use churust::prelude::*;
use churust::TestClient;
let app = Churust::server()
.routing(|r| {
r.get("/ping", |_c: Call| async { "pong" });
})
.build();
let res = TestClient::new(app).get("/ping").send().await;
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text(), "pong");§Feature flags
Plugins live behind Cargo features (all off by default):
| Feature | Enables |
|---|---|
json | churust_json — Json<T> + ContentNegotiation |
logging | churust_logging — CallLogging |
cors | churust_cors — Cors |
auth | churust_auth — Auth + Principal<P> |
tls | rustls TLS support in churust_core |
full | all four plugins |
[dependencies]
churust = { version = "0.2", features = ["full"] }No separate tokio entry is needed: the runtime is re-exported as
tokio, and #[churust::main] uses that re-export.
Bring the common items into scope with prelude.
§The #[churust::main] attribute
Builds a multi-threaded tokio runtime and blocks on the async body — the
Churust equivalent of #[tokio::main]:
#[churust::main]
async fn main() -> std::io::Result<()> {
use churust::prelude::*;
let _app = Churust::server().build();
Ok(())
}Re-exports§
pub use tokio;pub use churust_auth as auth;pub use churust_client as client;pub use churust_compression as compression;pub use churust_cors as cors;pub use churust_json as json;pub use churust_logging as logging;pub use churust_openapi as openapi;pub use churust_ratelimit as ratelimit;pub use churust_redis as redis;pub use churust_templates as templates;
Modules§
- app
- Application assembly: the
Churustentry point, theAppBuilderDSL, the immutableApp, thePlugintrait, and the resolvedServerConfig. - body
- The response
Body: either a fully-bufferedBytespayload or a lazy stream of byte chunks (for files, large/dynamic responses, SSE, etc.). - call
- The per-request
Callcontext — the single object every handler receives. - config
- Layered configuration: defaults <
churust.toml< env (CHURUST_*) < code. - cookie
- Cookies: reading a request’s, and building
Set-Cookie. Cookies: reading them off a request and buildingSet-Cookie. - engine
- The hyper-based HTTP/1.1 serving engine that drives an
Appover a real socket. - error
- The status-carrying
Errortype and the crate-wideResultalias. - extract
- Extractors: typed handler arguments derived from a
Call. - fs
- Static file serving (
StaticFiles). Enabled by thefsfeature. Static file serving (featurefs). - guard
- Route guards — predicates that select among routes sharing a method and path. Route guards: predicates that decide whether a registered route may serve a request, beyond matching its method and path.
- handler
- Handlers: the
Handlertrait, handler closures, and the glue that turns extractor closures into stored handlers. - http3
- HTTP/3 over QUIC. Enabled by the
http3feature. HTTP/3 over QUIC (featurehttp3). HTTP/3 over QUIC (featurehttp3). - identity
- Login, logout, and the two deadlines that end a login. Who the visitor is: login, logout, and the two deadlines that end a login.
- multipart
multipart/form-databodies. Enabled by themultipartfeature.multipart/form-databodies (featuremultipart).multipart/form-databodies (featuremultipart) — file uploads.- path
- Percent-decoding and canonicalisation for URL path segments. Percent-decoding for URL path segments.
- pipeline
- The request pipeline:
Middleware, thePhaseordering, theNextcontinuation, and theEndpointterminal. - prelude
- Common imports for everyday Churust apps.
- response
- The buffered
Responsetype and theIntoResponseconversion trait. - router
- The trie-based
Router, itsMatchresult, and theRouteBuilderDSL used insideAppBuilder::routing. - security
- Security response headers applied by default. See
SecurityHeaders. Security response headers, applied to every response by default. - session
- Sessions carried by a cookie. Sessions: per-visitor state carried by a cookie.
- state
- Type-keyed shared application state (a minimal DI registry).
- test
- In-process test harness. Drives
App::processdirectly — no socket bind. - tls
- TLS support (feature
tls). Loads a PEM cert chain + private key and builds atokio_rustls::TlsAcceptorwith rustls’ safe defaults. - ws
- WebSocket types (
WebSocket,WebSocketUpgrade,ws::Message). Enabled by thewsfeature. WebSocket support (featurews).
Structs§
- App
- An assembled, immutable, cheaply-cloneable application.
- AppBuilder
- The fluent builder for an application, returned by
Churust::server. - Authenticated
- An extractor that requires a logged-in visitor, yielding their id.
- Bearer
Token - Extracts the token from an
Authorization: Bearer <token>header. - Call
- Per-request context: the single object a handler receives (Ktor-style).
- Churust
- The framework entry point — a zero-sized namespace for starting an
AppBuilder. - Config
- The fully-resolved application configuration.
- Cookie
- A cookie to send with
Response::with_cookie. - Cookie
Store - Keeps the whole session in the cookie, signed with HMAC-SHA256 so a client cannot edit it.
- Error
- A handler/framework error carrying the HTTP status to respond with.
- Field
- One part of a streamed
multipart/form-databody. - Form
- Deserializes an
application/x-www-form-urlencodedrequest body intoT. - Header
- Extracts a single named header, parsed into
T. - Identities
- Installs the identity layer. See the module docs.
- Identity
- A handle to the current visitor’s identity.
- Multipart
- A parsed
multipart/form-databody. - Multipart
Stream - An incremental
multipart/form-dataparser. - Next
- The remaining middleware chain plus the terminal
Endpoint. - Params
- Captured path parameters, in the order the route captured them.
- Part
- One part of a
multipart/form-databody. - Path
- Extracts a single path parameter, parsed into
T. - Payload
- The request body as a stream, without buffering it.
- Peer
Addr - The address the connection came from, seeded by the engine.
- Query
- Deserializes the URL query string into
T. - Response
- A fully-buffered HTTP response: status line, headers, and an in-memory body.
- Route
Body Limit - A per-route body cap, seeded into the call by
RouteBuilder::max_body_bytes. - Route
Builder - The route-definition DSL handed to the closure in
AppBuilder::routing. - Router
- A compiled, trie-based router mapping
(method, path)to a handler. - Security
Headers - Which security headers to add, and with what values.
- Server
Config - The server configuration resolved at build time and carried by an
App. - Server
Section - The
[server]configuration table. - Session
- A handle to the current visitor’s session.
- Sessions
- Installs session handling. See the module docs.
- State
- Extracts a shared handle to application state of type
T. - State
Map - A type-keyed registry holding at most one shared value per type — a minimal dependency-injection container.
- Static
Files - Serves files from a directory. Build with
StaticFiles::dir, then mount itshandleron a{path...}wildcard route. - Test
Client - An in-process test client bound to an assembled
App. - Test
Request - A builder for a single in-process test request.
- Test
Response - The response returned by the in-process pipeline, with inspection helpers.
- TlsSection
- The
[tls]configuration table: paths to a PEM certificate chain and private key. - WebSocket
- An established WebSocket connection, handed to the
on_upgradecallback. - WebSocket
Upgrade - Extractor that represents a pending WebSocket upgrade. A handler takes it as
an argument, then calls
on_upgrade.
Enums§
- Body
- A response body.
- Either
- Accept one of two extractors, whichever succeeds.
- Match
- The outcome of routing a
(method, path)pair against theRouter. - Path
Policy - What to do when a request path is a non-canonical spelling of a route.
- Phase
- The ordered insertion points for middleware (Ktor-style).
- Same
Site - The
SameSiteattribute.
Constants§
- SESSION_
ID_ KEY - The reserved key under which a server-side
SessionStorerecords which row, document or Redis key this session is.
Traits§
- From
Call - Extract a value by consuming the whole
Call. - From
Call Parts - Extract a value from a borrowed
&mut Call. - Guard
- A predicate over the request. See the module docs.
- Handler
- Anything that can handle a
Calland produce aResponse. - Header
Name - Names the header that a
Headerextractor reads. - Into
Error - Let a user error type be returned from a handler with
?. - Into
Handler - Bridge from a closure (or anything that is already a
Handler) into a value implementingHandler, so it can be passed toboxedand the router. - Into
Response - Convert a handler return value into a
Response. - Middleware
- A pipeline interceptor — one layer of the onion.
- Optional
From Call Parts - An extractor that can distinguish absent from malformed.
- Plugin
- A reusable bundle of behavior that installs itself into an
AppBuilderat build time — Churust’s analogue of Ktor’sinstall(Plugin). - Session
Store - Where session contents live between requests.
Functions§
- allow_
header_ value - Render an
Allowheader value from the methods explicitly registered for a path, adding the ones the dispatcher answers implicitly. - block
- Run a blocking operation without stalling the async runtime.
- boxed
- Box a
Handlerinto a shareableBoxHandlerfor storage in theRouter. - check_
body_ limit - Reject a body larger than the route’s cap, if it set one.
- secure_
compare - Compare two secrets without leaking their contents through timing.
Type Aliases§
- Body
Stream - A request body still arriving, as a stream of chunks.
- BoxGuard
- A boxed guard, as stored by the router.
- BoxHandler
- A type-erased, shared handler — the form the
Routerstores. Create one withboxed. - Endpoint
- The terminal of the pipeline: a function that routes the call and runs the matched handler.
- Result
- Crate-wide result type, defaulting the error to
Error.
Attribute Macros§
- main
- The async entry-point attribute (see the crate-level docs). Wraps
async fn mainin a tokio runtime. Turnsasync fn main()into a synchronous entry point that runs on a multi-threaded Tokio runtime.