In my case, this doesn't quite work. I need to create an (expensive) object. After creating this object, it can then serve routes. Is there a way to do this with rocket?
pub struct MyHandlerObj {};
impl MyHandlerObj {
pub fn new() -> MyHandlerObj {
// this is expensive, don't want to do it on every REST request
}
pub fn handler(&self or maybe &mut self, HTTP input) -> HTTP output {
// this here is the actual handler
}
}
Of course. Your struct is "managed state" which is documented for Rocket in the "State" section of the guide.
By way of a bigger example, in outline, I light up my Rocket like so:
// Instantiate the data model.
let model = Model {
// Whatever initialization
...
};
...
...
// Launch rocket with state to manage, in model, and some routes.
let rocket = rocket::ignite()
.manage(model)
.mount(
"/",
routes![
index,
...
api_trips,
...
logout,
login,
about,
],
)
.attach(Template::fairing())
.register(catchers![not_found])
.launch();
My "Model" there is a complicated struct with methods:
// Some data model for Rocket to use a state
struct Model {
// Whatever struct fields.
...
}
impl Model {
// Function(s) to be used by Rocket route
fn get(&self) -> WhateverType {
}
...
}
The model gets used by a routes like so:
#[get("/public/api/trips")]
fn api_trips(model: State<Model>) -> Json<Trips> {
// Get whatever from the model
let stuff = model.get();
...
Json(results)
}
You can call .manage() on rocket many times with different structs.