1

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

  • You should be able to access a `&MyConfig` via `_rocket.state::().unwrap()` after `_rocket` completes successfully (that is, graceful shutdown). AFAICS there is no way to retrieve an owned version, but you could wrap `MyConfig` into an `Arc` and `Arc::into_inner()` if you absolutely have to. – user2722968 Jul 31 '22 at 18:56

1 Answers1

1

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.

kmdreko
  • 42,554
  • 6
  • 57
  • 106