Estado Afix - Compartilhamento de Dados em Requisições
O middleware Affix State é utilizado para adicionar dados compartilhados ao Depot.
Para utilizar a funcionalidade Affix State, é necessário ativar o recurso affix-state
no Cargo.toml.
Análise Funcional
O Affix State oferece uma maneira simples de compartilhar dados durante o processamento de requisições. Ele permite que você:
Injete configurações globais ou dados compartilhados durante a fase de configuração de rotas
Acesse esses dados através do Depot em qualquer handler
Suporte a qualquer tipo clonável como dado de estado
Comparação com Outros Frameworks - Entendimento Rápido
Framework | Linguagem | Gerenciamento de Estado |
---|
Salvo (Affix State) | Rust | Armazenamento e acesso via Depot, suporte a múltiplos tipos |
Axum | Rust | Estado armazenado via Extension, abordagem similar mas com uso diferente |
Actix-web | Rust | Uso de App Data e Web::Data para estado compartilhado |
Gin | Go | Utiliza context.Set e context.Get para manipular dados |
Echo | Go | Gerencia estado compartilhado com context.Set e context.Get |
Spring | Java | Gerencia dependências via ApplicationContext ou anotação @Bean |
Quarkus | Java | Utiliza mecanismos CDI e injeção de dependência |
Express.js | JavaScript | Armazena estado global em app.locals ou req.app.locals |
Nest.js | JavaScript | Sistema de injeção de dependência para serviços compartilhados |
Koa.js | JavaScript | Armazena estado no nível da requisição usando ctx.state |
Cenários Comuns de Uso
- Compartilhamento de pool de conexões de banco de dados
- Compartilhamento de configurações de aplicação
- Compartilhamento de instâncias de cache
- Compartilhamento de clientes API
- Rastreamento global de contadores ou estados
A vantagem do Affix State está na sua simplicidade e flexibilidade, permitindo compartilhar facilmente qualquer tipo de dado entre diferentes rotas e handlers sem a necessidade de código boilerplate excessivo.
Código de Exemplo
affix-state/src/main.rs
use std::sync::Arc;
use std::sync::Mutex;
use salvo::prelude::*;
// Configuration structure with username and password
#[allow(dead_code)]
#[derive(Default, Clone, Debug)]
struct Config {
username: String,
password: String,
}
// State structure to hold a list of fail messages
#[derive(Default, Debug)]
struct State {
fails: Mutex<Vec<String>>,
}
#[handler]
async fn hello(depot: &mut Depot) -> String {
// Obtain the Config instance from the depot
let config = depot.obtain::<Config>().unwrap();
// Get custom data from the depot
let custom_data = depot.get::<&str>("custom_data").unwrap();
// Obtain the shared State instance from the depot
let state = depot.obtain::<Arc<State>>().unwrap();
// Lock the fails vector and add a new fail message
let mut fails_ref = state.fails.lock().unwrap();
fails_ref.push("fail message".into());
// Format and return the response string
format!("Hello World\nConfig: {config:#?}\nFails: {fails_ref:#?}\nCustom Data: {custom_data}")
}
#[tokio::main]
async fn main() {
// Initialize the tracing subscriber for logging
tracing_subscriber::fmt().init();
// Create a Config instance with default username and password
let config = Config {
username: "root".to_string(),
password: "pwd".to_string(),
};
// Set up the router with state injection and custom data
let router = Router::new()
// Use hoop to inject middleware and data into the request context
.hoop(
affix_state::inject(config)
// Inject a shared State instance into the request context
.inject(Arc::new(State {
fails: Mutex::new(Vec::new()),
}))
// Insert custom data into the request context
.insert("custom_data", "I love this world!"),
)
// Register the hello handler for the root path
.get(hello)
// Add an additional route for the path "/hello" with the same handler
.push(Router::with_path("hello").get(hello));
// Bind the server to port 5800 and start serving
let acceptor = TcpListener::new("0.0.0.0:5800").bind().await;
Server::new(acceptor).serve(router).await;
}