Application state

Application state

Overview

The main reason Tuono is fast is that it loads just the features that are needed for the project.

To define them, you need to fill the ApplicationState struct in the ./src/app.rs file, and they will be automatically available in all the handlers you will define across the application.

// src/app.rs

#[derive(Clone)]
pub struct ApplicationState {
    pub website_name: String,
	pub base_path: String
}

pub fn main() -> ApplicationState {
    let website_name = "tuono".to_string();
    let base_path = "http://localhost:3000".to_string();

    ApplicationState {
        website_name,
        base_path
    }
}

For simplicity, we’re using a String here, but you can add database connections or HTTP clients. Check out the API fetching tutorial for an example with an HTTP client.

Now the ApplicationState is available on all the handlers as following:

// src/routes/index.rs

#[tuono_lib::handler]
// The first argument always is the Request
// The ApplicationState arguments are optional. You can use just the ones you need
// to use in the handler (with no specific order).
async fn my_handler(req: Request, website_name: String) -> Response {
    ...
}
Edit page