Im using the Axum framework to build a simple rest server. I want to have a sort of an "App State" that will have some reusable components for some of my handlers to reuse/consume.
#![allow(incomplete_features)]
#![feature(async_fn_in_trait)]
use axum::{routing::post, Router};
use std::{net::SocketAddr, sync::Arc};
mod modules;
use modules::auth::handlers::login;
pub struct AppState<'a> {
user_credentials_repository: UserCredentialsRepository<'a>,
}
pub struct UserCredentialsRepository<'a> {
shared_name: &'a mut String,
}
impl<'a> UserCredentialsRepository<'a> {
pub fn new(shared_name: &'a mut String) -> UserCredentialsRepository<'a> {
UserCredentialsRepository { shared_name }
}
}
#[tokio::main]
async fn main() {
let mut name = String::from("Tom");
let mut user_credentials_repository = UserCredentialsRepository::new(&mut name);
let shared_state = Arc::new(AppState {
user_credentials_repository,
});
let app = Router::new()
.route("/login", post(login))
.with_state(shared_state);
let addr = SocketAddr::from(([127, 0, 0, 1], 7777));
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
Basically what I'm trying to achieve is to reuse a db session/connection instance. Im testing it out by trying to share a string first but it doesn't seem to work. I get the following errors:
`name` dropped here while still borrowed
and
argument requires that `name` is borrowed for `'static`
I have somewhat of an idea how lifetimes work but I'm guessing something inside ".with_state(...)" takes ownership over the value I'm passing and tries to drop it?