Rocket routes: struct fn instead of global fn

Overview - Rocket Programming Guide demonstrates how to register global functions as routes.

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?

Here's what rocket shows so far:

[macro magic]
pub fn some_handler(input data) -> output {
  ...
}

Here's what I need:

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
  }
}

Is there a way to do this using Rocket?

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.

2 Likes

"Managed State" is exactly what I was looking for. Thanks!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.