» Rust: Build a REST API with Rocket » 2. Development » 2.7 Config File

Config File

let c = Config {
    app: ApplicationConfig { port: 8000 },
    db: DBConfig {
        file_name: "test.db".to_string(),
        dsn: "mysql://test_user:test_pass@127.0.0.1:3306/lr_book".to_string(),
    },
};

As you may have noticed, hard-coded config items are potential security breaches. And they're hard to change and control after being built and deployed.

That's why you need a separate config file.

Add config.toml:

[app]
port = 8000

[db]
file_name = "test.db"
dsn = "mysql://test_user:test_pass@127.0.0.1:3306/lr_book"

Add toml dependency:

cargo add toml

Tip: TOML stands for Tom's Obvious Minimal Language.

Diff in Cargo.toml:

@@ -13,3 +13,4 @@ rocket = { version = "0.5.0", features = ["json"] }
 rusqlite = "0.31.0"
 serde = { version = "1.0.197", features = ["derive"] }
 serde_json = "1.0.114"
+toml = "0.8.11"

Add parse_config function in infrastructure/config/mod.rs:

@@ -1,3 +1,5 @@
+use std::{fs::File, io::Read};
+
 use serde::{Deserialize, Serialize};
 
 #[derive(Debug, Deserialize, Serialize)]
@@ -16,3 +18,11 @@ pub struct DBConfig {
 pub struct ApplicationConfig {
     pub port: i32,
 }
+
+pub fn parse_config(file_name: &str) -> Config {
+    let mut file = File::open(file_name).expect("Failed to open TOML config file");
+    let mut content = String::new();
+    file.read_to_string(&mut content)
+        .expect("Failed to read TOML config file");
+    toml::from_str(&content).expect("Failed to parse TOML config file")
+}

Use parse_config in main.rs:

@@ -6,17 +6,13 @@ mod application;
 mod domain;
 mod infrastructure;
 use crate::adapter::router::*;
-use crate::infrastructure::{ApplicationConfig, Config, DBConfig};
+use crate::infrastructure::parse_config;
+
+const CONFIG_FILE: &str = "config.toml";
 
 #[launch]
 fn rocket() -> _ {
-    let c = Config {
-        app: ApplicationConfig { port: 8000 },
-        db: DBConfig {
-            file_name: "test.db".to_string(),
-            dsn: "mysql://test_user:test_pass@127.0.0.1:3306/lr_book".to_string(),
-        },
-    };
+    let c = parse_config(CONFIG_FILE);
     let wire_helper = application::WireHelper::new(&c).expect("Failed to create WireHelper");
     let r = adapter::make_router(&wire_helper);
     rocket::build().manage(r).mount(

Hard-coded config items are moved into config.toml. Nice!

Caution: Do not directly track your config.toml file with Git, as this could potentially leak sensitive data. If necessary, only track the template of the configuration file.
e.g.

[app]
port = 8000

[db]
file_name = ""
dsn = ""