配置文件
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(),
},
};
你可能已经注意到了,硬编码的配置项是潜在的安全漏洞。而且一旦构建部署后,开发人员也很难改动控制它。
所以,你需要一个单独的配置文件。
添加 config.toml:
[app]
port = 8000
[db]
file_name = "test.db"
dsn = "mysql://test_user:test_pass@127.0.0.1:3306/lr_book"
添加 toml
依赖:
cargo add toml
提示: TOML 表示 Tom's Obvious Minimal Language。
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"
添加 parse_config
函数,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")
+}
使用 parse_config
,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(
硬编码的配置项被移到了 config.toml
中。不错!
警醒: 不要直接 git 提交 config.toml。可能会导致敏感数据泄露。如果非要提交的话,建议只提交配置格式模板。
比如:[app] port = 8000 [db] file_name = "" dsn = ""
Loading...
> 此处输出代码运行结果