Affix State
Affix State 中间件用于往 Depot 中添加共享数据.
示例代码
use salvo::prelude::*;
#[handler]
async fn hello(depot: &mut Depot) -> String {
let config = depot.obtain::<Config>().unwrap();
let custom_data = depot.get::<&str>("custom_data").unwrap();
format!(
"Hello World\nConfig: {:#?}\nCustom Data: {}",
config, custom_data
)
}
#[tokio::main]
async fn main() {
tracing_subscriber::fmt().init();
let acceptor = TcpListener::new("127.0.0.1:5800").bind().await;
Server::new(acceptor).serve(route()).await;
}
#[allow(dead_code)]
#[derive(Default, Clone, Debug)]
struct Config {
username: String,
password: String,
}
fn route() -> Router {
let config = Config {
username: "root".to_string(),
password: "pwd".to_string(),
};
Router::new()
.hoop(affix_state::inject(config).insert("custom_data", "I love this world!"))
.get(hello)
.push(Router::with_path("hello").get(hello))
}
[package]
name = "example-affix-state"
version = "0.1.0"
edition = "2021"
publish = false
[dependencies]
salvo = { workspace = true, features = ["affix-state"] }
tokio = { version = "1", features = ["macros"] }
tracing = "0.1"
tracing-subscriber = "0.3"