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);
}
運行結果:
axum 0.1.0 chh <1400152400@qq.com>
2. 讀取.env文件
項目根目錄新建 .env 文件,寫入如下代碼:
DATABASE_URL=mysql://postgres:123456@localhost:3306/test
Cargo.toml 文件配置導入以下第三方庫:
[dependencies] dotenv = "0.15.0"
main.rs
use dotenv::dotenv;
use std::env;
fn main() {
// 在訪問環(huán)境變量之前檢查一下,防止因讀取環(huán)境變量失敗導致程序恐慌。
// 先把 dotenv 導入,然后在程序開始的地方執(zhí)行 dotenv() 函數(shù)即可,這就會從當前目錄或父目錄中的 .env 文件中加載環(huán)境變量。
// 如果你想指定其它路徑,可以使用 crate 中提供的 from_filename 或 from_path 這兩個函數(shù)。
// 好,那么調(diào)用 dotenv() 之后為什么還要調(diào)用 ok() 方法?
// 首先,dotenv() 返回的是 Result<PathBuf> 類型,如果返回值不使用的話,就會發(fā)出一個警告:
// 調(diào)用 ok() 之后,會把 Result 轉化為 Option,而 Option 就不會產(chǎn)生未使用 Result 的警告了。
// 那么,為什么不使用 unwrap()?
// 因為在生產(chǎn)環(huán)境中,你不會使用 .env 這個文件,你應該使用真實的環(huán)境變量,這時 dotenv() 函數(shù)就會加載失敗,如果使用 unwrap(),那么你的程序就會停止運行。
// 所以這里使用 ok() 的目的就是當加載 dotenv 環(huán)境文件失敗的時候可以忽略錯誤。
dotenv().ok();
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL 沒有在 .env 文件里設置");
print!("{:?}", database_url);
}
運行結果:
"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 文件配置導入以下第三方庫:
[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);
}
運行結果:
"postgres://postgres:123456@localhost/test"
Log { debug: true, debug_sql: false, log_root: "/tmp" }
到此這篇關于Rust讀取配置文件的實現(xiàn)的文章就介紹到這了,更多相關Rust 讀取配置文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
使用環(huán)境變量實現(xiàn)Rust程序中的不區(qū)分大小寫搜索方式
本文介紹了如何在Rust中實現(xiàn)不區(qū)分大小寫的搜索功能,并通過測試驅動開發(fā)(TDD)方法逐步實現(xiàn)該功能,通過修改運行函數(shù)和獲取環(huán)境變量,程序可以根據(jù)環(huán)境變量控制搜索模式2025-02-02
Rust語言從入門到精通之Tokio的Channel深入理解
這篇文章主要為大家介紹了Rust語言從入門到精通之Tokio的Channel深入理解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-05-05
Rust使用libloader調(diào)用動態(tài)鏈接庫
這篇文章主要為大家介紹了Rust使用libloader調(diào)用動態(tài)鏈接庫示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09

