Skip to main content

Crate churust

Crate churust 

Source
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):

FeatureEnables
jsonchurust_json — Json<T> + ContentNegotiation
loggingchurust_logging — CallLogging
corschurust_cors — Cors
authchurust_auth — Auth + Principal<P>
tlsrustls TLS support in churust_core
fullall 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 Churust entry point, the AppBuilder DSL, the immutable App, the Plugin trait, and the resolved ServerConfig.
body
The response Body: either a fully-buffered Bytes payload or a lazy stream of byte chunks (for files, large/dynamic responses, SSE, etc.).
call
The per-request Call context — 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 building Set-Cookie.
engine
The hyper-based HTTP/1.1 serving engine that drives an App over a real socket.
error
The status-carrying Error type and the crate-wide Result alias.
extract
Extractors: typed handler arguments derived from a Call.
fs
Static file serving (StaticFiles). Enabled by the fs feature. Static file serving (feature fs).
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 Handler trait, handler closures, and the glue that turns extractor closures into stored handlers.
http3
HTTP/3 over QUIC. Enabled by the http3 feature. HTTP/3 over QUIC (feature http3). HTTP/3 over QUIC (feature http3).
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-data bodies. Enabled by the multipart feature. multipart/form-data bodies (feature multipart). multipart/form-data bodies (feature multipart) — file uploads.
path
Percent-decoding and canonicalisation for URL path segments. Percent-decoding for URL path segments.
pipeline
The request pipeline: Middleware, the Phase ordering, the Next continuation, and the Endpoint terminal.
prelude
Common imports for everyday Churust apps.
response
The buffered Response type and the IntoResponse conversion trait.
router
The trie-based Router, its Match result, and the RouteBuilder DSL used inside AppBuilder::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::process directly — no socket bind.
tls
TLS support (feature tls). Loads a PEM cert chain + private key and builds a tokio_rustls::TlsAcceptor with rustls’ safe defaults.
ws
WebSocket types (WebSocket, WebSocketUpgrade, ws::Message). Enabled by the ws feature. WebSocket support (feature ws).

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.
BearerToken
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.
CookieStore
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-data body.
Form
Deserializes an application/x-www-form-urlencoded request body into T.
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-data body.
MultipartStream
An incremental multipart/form-data parser.
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-data body.
Path
Extracts a single path parameter, parsed into T.
Payload
The request body as a stream, without buffering it.
PeerAddr
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.
RouteBodyLimit
A per-route body cap, seeded into the call by RouteBuilder::max_body_bytes.
RouteBuilder
The route-definition DSL handed to the closure in AppBuilder::routing.
Router
A compiled, trie-based router mapping (method, path) to a handler.
SecurityHeaders
Which security headers to add, and with what values.
ServerConfig
The server configuration resolved at build time and carried by an App.
ServerSection
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.
StateMap
A type-keyed registry holding at most one shared value per type — a minimal dependency-injection container.
StaticFiles
Serves files from a directory. Build with StaticFiles::dir, then mount its handler on a {path...} wildcard route.
TestClient
An in-process test client bound to an assembled App.
TestRequest
A builder for a single in-process test request.
TestResponse
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_upgrade callback.
WebSocketUpgrade
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 the Router.
PathPolicy
What to do when a request path is a non-canonical spelling of a route.
Phase
The ordered insertion points for middleware (Ktor-style).
SameSite
The SameSite attribute.

Constants§

SESSION_ID_KEY
The reserved key under which a server-side SessionStore records which row, document or Redis key this session is.

Traits§

FromCall
Extract a value by consuming the whole Call.
FromCallParts
Extract a value from a borrowed &mut Call.
Guard
A predicate over the request. See the module docs.
Handler
Anything that can handle a Call and produce a Response.
HeaderName
Names the header that a Header extractor reads.
IntoError
Let a user error type be returned from a handler with ?.
IntoHandler
Bridge from a closure (or anything that is already a Handler) into a value implementing Handler, so it can be passed to boxed and the router.
IntoResponse
Convert a handler return value into a Response.
Middleware
A pipeline interceptor — one layer of the onion.
OptionalFromCallParts
An extractor that can distinguish absent from malformed.
Plugin
A reusable bundle of behavior that installs itself into an AppBuilder at build time — Churust’s analogue of Ktor’s install(Plugin).
SessionStore
Where session contents live between requests.

Functions§

allow_header_value
Render an Allow header 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 Handler into a shareable BoxHandler for storage in the Router.
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§

BodyStream
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 Router stores. Create one with boxed.
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 main in a tokio runtime. Turns async fn main() into a synchronous entry point that runs on a multi-threaded Tokio runtime.