I have a variable that gets initialized in main
(line 9) and I want to access a reference to this variable inside of one of my route handlers.
#[get("/")]
fn index() -> String {
return fetch_data::fetch(format!("posts"), &redis_conn).unwrap(); // How can I get redis_conn?
}
fn main() {
let redis_conn = fetch_data::get_redis_connection(); // initialized here
rocket::ignite().mount("/", routes![index]).launch();
}
In other languages, this problem would be solvable by using global variables.
Please read the Rocket documentation, specifically the section on state.
Use State
and Rocket::manage
to have shared state:
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use]
extern crate rocket; // 0.4.2
use rocket::State;
struct RedisThing(i32);
#[get("/")]
fn index(redis: State<RedisThing>) -> String {
redis.0.to_string()
}
fn main() {
let redis = RedisThing(42);
rocket::ignite()
.manage(redis)
.mount("/", routes![index])
.launch();
}
If you want to mutate the value inside the State
, you will need to wrap it in a Mutex
or other type of thread-safe interior mutability.
See also:
this problem would be solvable by using global variables.
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With