#serde #environment #env-var #variables #expand #parse #deserialize-with

serde-with-expand-env

使用deserialize_with在serdecrate中解析环境变量

3个版本 (稳定)

1.1.0 2020年2月21日
1.0.0 2019年12月31日
0.1.0 2019年12月13日

#1290 in 编码

Download history 163/week @ 2024-03-24 205/week @ 2024-03-31 251/week @ 2024-04-07 156/week @ 2024-04-14 302/week @ 2024-04-21 194/week @ 2024-04-28 107/week @ 2024-05-05 234/week @ 2024-05-12 223/week @ 2024-05-19 400/week @ 2024-05-26 277/week @ 2024-06-02 427/week @ 2024-06-09 166/week @ 2024-06-16 373/week @ 2024-06-23 344/week @ 2024-06-30 262/week @ 2024-07-07

1,159 每月下载量
用于 15 个crate(3个直接使用)

MIT 协议

7KB

serde-with-expand-env

Build Status MIT licensed

使用deserialize_withserdecrate中解析环境变量。

示例

use std::env;
use serde_json;
use serde::Deserialize;
use serde_with_expand_env::with_expand_envs;

#[derive(Deserialize, Debug)]
struct Test {
    #[serde(deserialize_with="with_expand_envs")]
    number: usize,
    #[serde(deserialize_with="with_expand_envs")]
    string: String,
    #[serde(deserialize_with="with_expand_envs")]
    default: usize,
}

fn main() {
    let serialized = r#"{"number": "$NUMBER",
                         "string": "my string: $STRING",
                         "default": "${DEFAULT:-42}"
                      }"#;

    // No envs set will fail with enviroment variable not found
    assert_eq!(serde_json::from_str::<Test>(&serialized).is_err(), true);

    env::set_var("NUMBER", "42");
    env::set_var("STRING", "hacker");
    let deserialized: Test = serde_json::from_str(&serialized).unwrap();

    assert_eq!(deserialized.number, 42);
    assert_eq!(deserialized.string, "my string: hacker");
    assert_eq!(deserialized.default, 42);

    env::set_var("DEFAULT", "4200");
    let deserialized: Test = serde_json::from_str(&serialized).unwrap();
    assert_eq!(deserialized.default, 4200);

    // Invalid number
    env::set_var("NUMBER", "cuarentaydos");
    env::set_var("STRING", "42");
    assert_eq!(serde_json::from_str::<Test>(&serialized).is_err(), true);
}

更多示例在examples

依赖

~0.5–1.5MB
~28K SLoC