Reputation: 15
I want to be able to do something with my state once the server starts shutting down
example:
struct MyConfig {
user_val: String
}
#[get("/hello")]
fn hello(config: &State<MyConfig>) -> Result<String, error::Error> {
//do stuff
Ok(&config.user_val)
}
#[rocket::main]
async fn main() -> Result<(), error::Error> {
let config = MyConfig{user_val: "hello".to_string()};
let _rocket = rocket::build()
.manage(config) //cant pass as borrow because it wont live long enough
.mount("/", routes![hello])
.launch()
.await?;
println!("{}", &config.user_val); //cant access because value moved
Ok(())
}
The result should be when I shut down the program it prints user_val(I dont want to clone)
but after setting it as a state its no longer accessible after the server ends
Upvotes: 1
Views: 564
Reputation: 60517
You can get access to the config by using .state()
afterwards:
struct MyConfig {
user_val: String,
}
#[rocket::main]
async fn main() -> Result<(), rocket::error::Error> {
let config = MyConfig { user_val: "hello".to_string()};
let rocket = rocket::build()
.manage(config)
.ignite() // this puts it in the post-launch state for testing
.await?;
let config = rocket.state::<MyConfig>().unwrap();
println!("{}", config.user_val);
Ok(())
}
hello
Although, config
will be a reference. You aren't able to take ownership back after giving it to Rocket. If you need ownership, you'll have to .clone()
the config or store it in an Arc
before managing so you can .clone()
that to avoid duplicating the underlying config data.
Upvotes: 2