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)文章
如何使用VSCode配置Rust開發(fā)環(huán)境(Rust新手教程)
這篇文章主要介紹了如何使用VSCode配置Rust開發(fā)環(huán)境(Rust新手教程),本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07Rust Atomics and Locks并發(fā)基礎(chǔ)理解
這篇文章主要為大家介紹了Rust Atomics and Locks并發(fā)基礎(chǔ)理解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02Rust中的Cargo構(gòu)建、運(yùn)行、調(diào)試
Cargo是rustup安裝后自帶的,Cargo?是?Rust?的構(gòu)建系統(tǒng)和包管理器,這篇文章主要介紹了Rust之Cargo構(gòu)建、運(yùn)行、調(diào)試,需要的朋友可以參考下2022-09-09教你使用RustDesk?搭建一個自己的遠(yuǎn)程桌面中繼服務(wù)器
這篇文章主要介紹了RustDesk?搭建一個自己的遠(yuǎn)程桌面中繼服務(wù)器,主要包括服務(wù)端安裝和客戶端配置方法,配置好相關(guān)操作輸入控制碼即可發(fā)起遠(yuǎn)程或文件傳輸,本文通過圖文給大家講解的非常詳細(xì),需要的朋友可以參考下2022-08-08