Skip to main content

Module state

Module state 

Source
Expand description

Shared application state and state-aware routing.

AppWithState<S> combines a typed state value (database pools, config, caches) with route registration. Routes are tried first; requests that do not match fall through to the built-in App controller chain (static files, healthz, metrics, …).

State is stored as an Arc<S> and shared across all handlers. Handlers receive an immutable &S reference alongside the request context.

§Example

use rust_web_server::state::AppWithState;
use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};
use rust_web_server::range::Range;
use rust_web_server::mime_type::MimeType;
use rust_web_server::core::New;

struct AppState {
    greeting: String,
}

let app = AppWithState::new(AppState { greeting: "Hello".to_string() })
    .get("/greet", |_req, _params, _conn, state| {
        let mut r = Response::new();
        r.status_code = *STATUS_CODE_REASON_PHRASE.n200_ok.status_code;
        r.reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok.reason_phrase.to_string();
        r.content_range_list = vec![
            Range::get_content_range(
                state.greeting.as_bytes().to_vec(),
                MimeType::TEXT_PLAIN.to_string(),
            )
        ];
        r
    })
    .get("/users/:id", |_req, params, _conn, state| {
        let id = params.get("id").unwrap_or("?");
        let body = format!("{}, user {}!", state.greeting, id);
        let mut r = Response::new();
        r.status_code = *STATUS_CODE_REASON_PHRASE.n200_ok.status_code;
        r.reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok.reason_phrase.to_string();
        r.content_range_list = vec![
            Range::get_content_range(body.into_bytes(), MimeType::TEXT_PLAIN.to_string())
        ];
        r
    });

Structs§

AppWithState
An Application that combines user-defined state-aware routes with the built-in App controller chain as a fallback.