Skip to main content

to_with_state

Function to_with_state 

Source
pub fn to_with_state<St, In, F, Args>(handler: F) -> Route<St, In>
where St: State, In: 'static, F: HandlerSt<St, In, Args> + 'static, Args: FromRequest<St> + 'static, Args::Error: WebResponseError<St, St::Error>,
Expand description

Create a new route with a state-aware handler.

The handler receives a shared reference to the application state, followed by the request state and any request extractors. Use to() when the handler only needs request extractors.

use std::convert::Infallible;
use ntex::web::{self, WebRequest};

struct AppState {
    greeting: &'static str,
}

impl web::State for AppState {
    type Error = web::DefaultError;
}

async fn index(
    state: &AppState,
    request_state: usize,
    name: web::types::Path<String>,
) -> String {
    let _ = request_state;
    format!("{}, {}!", state.greeting, name.into_inner())
}

web::App::<AppState>::new().service(
    web::resource("/{name}")
        .filter(async |req: WebRequest<()>| {
            Ok::<_, Infallible>(req.map_state(|_| 10usize))
        })
        .route(web::to_with_state(index))
);