Rust讀取配置文件的實現(xiàn)
1. 讀取Cargo.toml文件
Cargo.toml
文件配置如下:
[package] name = "axum" version = "0.1.0" authors = ["chh <1400152400@qq.com>"] edition = "2021"
main.rs
fn main() { let name = env!("CARGO_PKG_NAME"); let version = env!("CARGO_PKG_VERSION"); let author = env!("CARGO_PKG_AUTHORS"); println!("{} {} {}", &name, &version, &author); }
運(yùn)行結(jié)果:
axum 0.1.0 chh <1400152400@qq.com>
2. 讀取.env文件
項目根目錄新建 .env
文件,寫入如下代碼:
DATABASE_URL=mysql://postgres:123456@localhost:3306/test
Cargo.toml
文件配置導(dǎo)入以下第三方庫:
[dependencies] dotenv = "0.15.0"
main.rs
use dotenv::dotenv; use std::env; fn main() { // 在訪問環(huán)境變量之前檢查一下,防止因讀取環(huán)境變量失敗導(dǎo)致程序恐慌。 // 先把 dotenv 導(dǎo)入,然后在程序開始的地方執(zhí)行 dotenv() 函數(shù)即可,這就會從當(dāng)前目錄或父目錄中的 .env 文件中加載環(huán)境變量。 // 如果你想指定其它路徑,可以使用 crate 中提供的 from_filename 或 from_path 這兩個函數(shù)。 // 好,那么調(diào)用 dotenv() 之后為什么還要調(diào)用 ok() 方法? // 首先,dotenv() 返回的是 Result<PathBuf> 類型,如果返回值不使用的話,就會發(fā)出一個警告: // 調(diào)用 ok() 之后,會把 Result 轉(zhuǎn)化為 Option,而 Option 就不會產(chǎn)生未使用 Result 的警告了。 // 那么,為什么不使用 unwrap()? // 因為在生產(chǎn)環(huán)境中,你不會使用 .env 這個文件,你應(yīng)該使用真實的環(huán)境變量,這時 dotenv() 函數(shù)就會加載失敗,如果使用 unwrap(),那么你的程序就會停止運(yùn)行。 // 所以這里使用 ok() 的目的就是當(dāng)加載 dotenv 環(huán)境文件失敗的時候可以忽略錯誤。 dotenv().ok(); let database_url = env::var("DATABASE_URL").expect("DATABASE_URL 沒有在 .env 文件里設(shè)置"); print!("{:?}", database_url); }
運(yùn)行結(jié)果:
"mysql://postgres:123456@localhost:3306/test"
3. 讀取自定義toml文件
項目根目錄新建 config.toml
文件,寫入如下代碼:
[database] url = "postgres://postgres:123456@localhost/test" [log] debug = true debug_sql = false log_root = "/tmp"
Cargo.toml
文件配置導(dǎo)入以下第三方庫:
[dependencies] config = "0.13.1" toml = "0.5.9" lazy_static = "1.4" serde = "1.0" serde_derive = "1.0"
新建 settings.rs
,寫入如下代碼:
use std::{fs::File, io::Read}; use lazy_static::lazy_static; use serde::Deserialize; #[derive(Debug, Deserialize)] pub struct Database { pub url: String, } #[derive(Debug, Deserialize)] pub struct Log { pub debug: bool, pub debug_sql: bool, pub log_root: String, } #[derive(Debug, Deserialize)] pub struct Settings { pub database: Database, pub log: Log, } impl Default for Settings { fn default() -> Self { let file_path = "config.toml"; let mut file = match File::open(file_path) { Ok(f) => f, Err(e) => panic!("no such file {} exception:{}", file_path, e) }; let mut str_val = String::new(); match file.read_to_string(&mut str_val) { Ok(s) => s, Err(e) => panic!("Error Reading file: {}", e) }; toml::from_str(&str_val).expect("Parsing the configuration file failed"); } } impl Settings { pub fn get<'a>() -> &'a Self { // 給靜態(tài)變量延遲賦值的宏 lazy_static! { static ref CACHE: Settings = Settings::default(); } &CACHE } }
main.rs
代碼如下:
use crate::settings::Settings; mod settings; fn main() { let setting = Settings::get(); println!("{:?}", setting.database.url); println!("{:?}", setting.log); }
運(yùn)行結(jié)果:
"postgres://postgres:123456@localhost/test"
Log { debug: true, debug_sql: false, log_root: "/tmp" }
到此這篇關(guān)于Rust讀取配置文件的實現(xiàn)的文章就介紹到這了,更多相關(guān)Rust 讀取配置文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Rust中的Iterator和IntoIterator介紹及應(yīng)用小結(jié)
Iterator即迭代器,它可以用于對數(shù)據(jù)結(jié)構(gòu)進(jìn)行迭代,被迭代的數(shù)據(jù)結(jié)構(gòu)是可迭代的(iterable),所謂的可迭代就是這個數(shù)據(jù)結(jié)構(gòu)有返回迭代器的方法,這篇文章主要介紹了Rust中的Iterator和IntoIterator介紹及應(yīng)用,需要的朋友可以參考下2023-07-07Rust?Atomics?and?Locks內(nèi)存序Memory?Ordering詳解
這篇文章主要為大家介紹了Rust?Atomics?and?Locks內(nèi)存序Memory?Ordering詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02rust的nutyp驗證和validator驗證數(shù)據(jù)的方法示例詳解
本文介紹了在Rust語言中,如何使用nuType和validator兩種工具來對Cargo.toml和modules.rs文件進(jìn)行驗證,通過具體的代碼示例和操作步驟,詳細(xì)解釋了驗證過程和相關(guān)配置,幫助讀者更好地理解和掌握使用這兩種驗證工具的方法,更多Rust相關(guān)技術(shù)資訊,可繼續(xù)關(guān)注腳本之家2024-09-09