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

serde-with-expand-env

Parse environment variables in serde crate using deserialize_with

3 releases (stable)

1.1.0 Feb 21, 2020
1.0.0 Dec 31, 2019
0.1.0 Dec 13, 2019

#2525 in Parser implementations

Download history 639/week @ 2024-07-23 156/week @ 2024-07-30 594/week @ 2024-08-06 793/week @ 2024-08-13 756/week @ 2024-08-20 991/week @ 2024-08-27 846/week @ 2024-09-03 796/week @ 2024-09-10 549/week @ 2024-09-17 913/week @ 2024-09-24 1176/week @ 2024-10-01 918/week @ 2024-10-08 501/week @ 2024-10-15 542/week @ 2024-10-22 1053/week @ 2024-10-29 1282/week @ 2024-11-05

3,458 downloads per month
Used in 17 crates (3 directly)

MIT license

7KB

serde-with-expand-env

Build Status MIT licensed

Parse environment variables in serde crate using deserialize_with.

Example:

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);
}

more examples in examples

Dependencies

~0.5–1.4MB
~27K SLoC