I'm starting to learn Rust and the rocket framework https://crates.io/crates/rocket.
I have a dumb question that I can't figure out.
How do I return my_universe that I created on the first line of main() when calling GET /universe/ports/21?
fn main() {
let my_universe = universe::model::Universe::new();
rocket::ignite().mount("/universe", routes![ports]).launch();
}
#[get("/ports/<id>")]
fn ports(id: u16) -> universe::model::Universe {
// need to return my_universe here
}
The issue I'm having is that if I define my_universe within the route controller ports(), it'll recreate the my_universe object on each request. Instead, I need the route to return the same my_universe object on each request
Sharing non-mutable state in rocket is fairly easy. You can add the state with
manageduring the build of rocket.If you want to return this state in a route you will have to add both
serdeas a dependency and thejsonfeature of rocket.You can now annotate your
structwithSerializeso we can send it as a JSON response later.And access this state in your route with a
&Stateparameter.Here we can access the
innervalue of the state and return it asJson.So far, the state is immutable and can not be changed in the route which might not be what you want. Consider wrapping your state into a
Mutexto allow for interior mutability.