serde-with-expand-env

Crates.ioserde-with-expand-env
lib.rsserde-with-expand-env
version1.1.0
sourcesrc
created_at2019-12-13 03:38:29.904363
updated_at2020-02-21 08:50:37.701608
descriptionParse environment variables in serde crate using deserialize_with.
homepage
repositoryhttps://github.com/Roger/serde-with-expand-env
max_upload_size
id188971
size21,623
roger (Roger)

documentation

README

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

Commit count: 12

cargo fmt