e9571_config-reader 0.1.0

A simple Rust crate to read config.json from executable directory
Documentation
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use serde_json;

// 读取 config.json 并解析为 HashMap<String, String>
pub fn read_config() -> Result<HashMap<String, String>, Box<dyn std::error::Error>> {
    // 获取可执行文件路径
    let exe_path = std::env::current_exe()?;
    // 提取目录路径
    let exe_dir = exe_path.parent().ok_or("Failed to get executable directory")?;
    // 拼接 config.json 路径
    let config_path = exe_dir.join("config.json");

    // 检查文件是否存在
    if !config_path.exists() {
        return Err(format!("config.json not found in {:?}", exe_dir).into());
    }

    // 打开文件
    let mut file = File::open(&config_path)?;

    // 读取文件内容到字符串
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;

    // 解析 JSON 为 HashMap
    let config: HashMap<String, String> = serde_json::from_str(&contents)?;

    Ok(config)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_read_config() {
        // 测试需要 config.json 存在,建议在测试前创建
        match read_config() {
            Ok(config) => {
                assert!(config.contains_key("apiURL"));
                assert!(config.contains_key("apiKey"));
            }
            Err(e) => panic!("Test failed: {}", e),
        }
    }
}