rust rocket读取自定义配置

作者: adm 分类: Rust 发布时间: 2024-07-09

rust rocket读取自定义配置,以自定义端口为例
Rocket.toml

[development]
port = 8200

[production]
port = 80

cargo.toml

[dependencies]
rocket = { version = "0.5.1", features = ["json"] }
serde = { version = "1.0.204", features = ["derive"] }
#deadpool-redis = { version = "0.9", features = ["serde"] }
#redis = { version = "0.21", default-features = false, features = ["tls"] }
figment = "0.10.8"
config = "0.14.0"
toml = "0.5"

main.rs

#[macro_use] extern crate rocket;

use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
use rocket::{Config, Build};
use rocket::fairing::AdHoc;
use rocket::{figment::Figment, serde::{Deserialize, Serialize, json::Json}};
use rocket::serde::json::serde_json::from_reader;
use toml::from_str;

//访问链接示例:http://localhost:8000/hello
#[get("/hello")]
fn hello(name: &str, age: u8, is_male: bool) -> String {
    if is_male {
        format!("姓名 {} ,年龄 {}, 性别 男!", name, age)
    } else {
        format!("姓名 {} ,年龄 {}, 性别 女!", name, age)
    }
}

#[derive(Deserialize)]
struct MyConfig {
    development: DevConfig,
    production: ProdConfig,
}

#[derive(Deserialize)]
struct DevConfig {
    port: u16,
}

#[derive(Deserialize)]
struct ProdConfig {
    port: u16,
}




fn load_config() -> Result> {
    let mut file = File::open("Rocket.toml")?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    Ok(from_str(&contents)?)
}



#[launch]
fn rocket() -> _ {
    let config = load_config().expect("Failed to load config");
    let port = config.development.port;
    println!("x = {}", config.development.port);

    rocket::custom(Config::figment()
        .merge(("port", port))
    )
        .mount("/", routes![hello])
}

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!