e9571_config_reader/
lib.rs

1use std::collections::HashMap;
2use std::fs::File;
3use std::io::Read;
4use std::path::Path;
5use serde_json;
6
7// 读取 config.json 并解析为 HashMap<String, String>
8pub fn read_config() -> Result<HashMap<String, String>, Box<dyn std::error::Error>> {
9    // 获取可执行文件路径
10    let exe_path = std::env::current_exe()?;
11    // 提取目录路径
12    let exe_dir = exe_path.parent().ok_or("Failed to get executable directory")?;
13    // 拼接 config.json 路径
14    let config_path = exe_dir.join("config.json");
15
16    // 检查文件是否存在
17    if !config_path.exists() {
18        return Err(format!("config.json not found in {:?}", exe_dir).into());
19    }
20
21    // 打开文件
22    let mut file = File::open(&config_path)?;
23
24    // 读取文件内容到字符串
25    let mut contents = String::new();
26    file.read_to_string(&mut contents)?;
27
28    // 解析 JSON 为 HashMap
29    let config: HashMap<String, String> = serde_json::from_str(&contents)?;
30
31    Ok(config)
32}
33
34#[cfg(test)]
35mod tests {
36    use super::*;
37
38    #[test]
39    fn test_read_config() {
40        // 测试需要 config.json 存在,建议在测试前创建
41        match read_config() {
42            Ok(config) => {
43                assert!(config.contains_key("apiURL"));
44                assert!(config.contains_key("apiKey"));
45            }
46            Err(e) => panic!("Test failed: {}", e),
47        }
48    }
49}