Axum middleware shares a pool of database connections #2819
-
SummaryHow do I share an AXUM database connection pool to middleware? Should I call the database connection pool in the middleware and use it? For example, when I'm using JWT for user authentication, after I decode the token and get the unique identification information of the user, do I need to perform a database query to check if this person exists? Or, when I need to implement a permission system, do I need to query the database to see if this person has access rights? Isn't this all required to import the database connection pool into the middleware and use it? This issue has troubled me for a long time, and I hope someone can teach me. axum version0.7.5 |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Found out |
Beta Was this translation helpful? Give feedback.
-
main.rs use axum::{
extract::{Request, State},
middleware::{self, Next},
response::Response,
routing::{get, Router},
};
use std::sync::Arc;
use tower::ServiceBuilder;
use tower_http::trace::TraceLayer;
// Assume DbPool and Config are already defined
#[derive(Clone, Debug)]
struct DbPool {
// Fields related to the database connection pool
}
#[derive(Clone, Debug)]
struct Config {
// Fields related to configuration information
}
// Shared state struct, containing database connection pool and configuration information
#[derive(Clone)]
struct SharedState {
db_pool: Arc<DbPool>,
config: Arc<Config>,
}
// Example root route handler function
async fn root_handler() -> &'static str {
"Welcome to the root!"
}
// Example handler function for another route
async fn other_handler() -> &'static str {
"Welcome to another route!"
}
// Middleware to print database connection information
async fn db_aware_middleware(
State(shared_state): State<Arc<SharedState>>,
request: Request<axum::body::BoxBody>,
next: Next<Router>,
) -> Response {
let response = next.run(request).await;
println!("Database pool: {:?}", shared_state.db_pool);
response.into_response()
}
// Middleware to print configuration information
async fn config_aware_middleware(
State(shared_state): State<Arc<SharedState>>,
request: Request<axum::body::BoxBody>,
next: Next<Router>,
) -> Response {
let response = next.run(request).await;
println!("Config: {:?}", shared_state.config);
response.into_response()
}
#[tokio::main]
async fn main() {
// Initialize the database connection pool and configuration information
let db_pool = Arc::new(DbPool {
// Initialize the database connection pool
});
let config = Arc::new(Config {
// Initialize the configuration information
});
let shared_state = Arc::new(SharedState {
db_pool,
config,
});
let app = Router::new()
// The root route uses the db_aware_middleware middleware
.nest(
"/",
Router::new()
.route("/", get(root_handler))
.layer(ServiceBuilder::new().layer(TraceLayer::new()))
.layer(middleware::from_fn_with_state(shared_state.clone(), db_aware_middleware)),
)
// Other routes use the config_aware_middleware middleware
.nest(
"/other",
Router::new()
.route("/", get(other_handler))
.layer(ServiceBuilder::new().layer(TraceLayer::new()))
.layer(middleware::from_fn_with_state(shared_state, config_aware_middleware)),
);
// Run the application
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app.into_make_service()).await.unwrap();
}` |
Beta Was this translation helpful? Give feedback.
main.rs
axum 0.7.5