Accessing the values of the default and custom configuration fields #2709
-
I admit I did not totally understand the page about configuration, but I did some experiments and wrote this article |
Beta Was this translation helpful? Give feedback.
Answered by
SergioBenitez
Jan 24, 2024
Replies: 1 comment 1 reply
-
You absolutely should not do the following in a route handler: let custom_a: String = rocket::Config::figment().extract_inner("custom_a").unwrap_or(String::from("some default")); Calling Instead, use use rocket::{State, fairing::AdHoc};
#[get("/")]
fn custom(config: &State<MyConfig>) -> String {
config.custom_a.clone()
}
#[derive(Deserialize)]
struct MyConfig {
custom_a: String,
}
#[launch]
fn rocket() -> _ {
rocket::build()
.mount("/", routes![custom])
.attach(AdHoc::config::<Config>())
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
szabgab
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You absolutely should not do the following in a route handler:
Calling
figment()
is expensive as it reads all of the files and does all of deserialization.Instead, use
AdHoc::config()
to extract the configuration in a typed fashion at launch time, then simply read it in a route: