Load config from file and use it in rust code everywhere

Viewed 1870

I'm new to rust and want to understand how to load config from file to use it in code.

In main.rs and other files i want to use config loaded from file:

mod config;
use crate::config::config;

fn main() {
  println!("{:?}", config);
}

In config.rs file i want to read backend.conf file once at runtime, check it and store it as immutable to use it everywhere. My attempts so far got me only errors:

use hocon::HoconLoader;
use serde::Deserialize;

#[derive(Deserialize, Debug)]
pub struct Config {
    pub host: String,
    pub port: String,
}

pub const config: Config = get_config(); //err: calls in constants are limited to constant functions, tuple structs and tuple variants

fn get_config() -> Config {
    let config: Config = HoconLoader::new() // err: could not evaluate constant pattern
        .load_file("./backend.conf")
        .expect("Config load err")
        .resolve()
        .expect("Config deserialize err");

    config
}

What i can't wrap my head around, is to how you should do it in rust?


As Netwave suggested this is how it works:

main.rs:

 #[macro_use]
   extern crate lazy_static;

    mod config;
    use crate::config::CONFIG;

    fn main() {
      println!("{:?}", CONFIG.host);
    }

config.rs:

use hocon::HoconLoader;
use serde::Deserialize;

#[derive(Deserialize, Debug)]
pub struct Config {
    pub host: String,
    pub port: String,
}

lazy_static! {
    pub static ref CONFIG: Config = get_config();
}

fn get_config() -> Config {
    let configs: Config = HoconLoader::new()
        .load_file("./backend.conf")
        .expect("Config load err")
        .resolve()
        .expect("Config deserialize err");

    configs
}

backend.config:

{
    host: "127.0.0.1"
    port: "3001"
}
1 Answers

Use lazy_static:

lazy_static!{
    pub static ref CONFIG: Config = get_config(); 
}

Alternatively, you may load it in the program entry point and attach it in some kind of context and pass it around where you need it.

Related