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_cors as cors;
pub use churust_json as json;
pub use churust_logging as logging;

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.
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).
handler
Handlers: the Handler trait, handler closures, and the glue that turns extractor closures into stored handlers.
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.
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.
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.
Error
A handler/framework error carrying the HTTP status to respond with.
Next
The remaining middleware chain plus the terminal Endpoint.
Path
Extracts a single path parameter, parsed into T.
Query
Deserializes the URL query string into T via serde_urlencoded.
Response
A fully-buffered HTTP response: status line, headers, and an in-memory body.
RouteBuilder
The route-definition DSL handed to the closure in AppBuilder::routing.
Router
A compiled, trie-based router mapping (method, path) to a handler.
ServerConfig
The server configuration resolved at build time and carried by an App.
ServerSection
The [server] configuration table.
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. Obtained inside the WebSocketUpgrade::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.
Match
The outcome of routing a (method, path) pair against the Router.
Phase
The ordered insertion points for middleware (Ktor-style).

Traits§

FromCall
Extract a value by consuming the whole Call.
FromCallParts
Extract a value from a borrowed &mut Call.
Handler
Anything that can handle a Call and produce a Response.
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.
Plugin
A reusable bundle of behavior that installs itself into an AppBuilder at build time — Churust’s analogue of Ktor’s install(Plugin).

Functions§

boxed
Box a Handler into a shareable BoxHandler for storage in the Router.

Type Aliases§

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.