Skip to main content

Environment

Struct Environment 

Source
pub struct Environment { /* private fields */ }
Expand description

Environment variable configuration source.

The Environment struct provides a flexible way to read configuration values from environment variables. It supports prefixes, custom separators, case sensitivity control, and field-specific mappings.

§Examples

§Basic Usage

use gonfig::{Environment, ConfigBuilder};
use serde::Deserialize;

#[derive(Deserialize)]
struct Config {
    database_url: String,
    port: u16,
}

std::env::set_var("APP_DATABASE_URL", "postgres://localhost/db");
std::env::set_var("APP_PORT", "5432");

let config: Config = ConfigBuilder::new()
    .add_source(Box::new(Environment::new().with_prefix("APP")))
    .build()
    .unwrap();

§Advanced Configuration

use gonfig::Environment;

let env = Environment::new()
    .with_prefix("MYAPP")
    .separator("__")  // Use double underscore
    .case_sensitive(true)
    .override_with("database_url", "postgres://override/db")
    .with_field_mapping("db_url", "CUSTOM_DB_CONNECTION");

Implementations§

Source§

impl Environment

Source

pub fn new() -> Self

Create a new environment variable source with default settings.

Default configuration:

  • No prefix
  • Separator: "_"
  • Case sensitive: false (environment variables are converted to uppercase)
  • No overrides or field mappings
§Examples
use gonfig::Environment;

let env = Environment::new();
Source

pub fn with_prefix(self, prefix: impl Into<String>) -> Self

Set the environment variable prefix.

When a prefix is set, environment variables will be expected in the format {PREFIX}{SEPARATOR}{FIELD_NAME}. For example, with prefix “APP” and separator “_”, a field named database_url would map to APP_DATABASE_URL.

§Examples
use gonfig::Environment;

let env = Environment::new().with_prefix("MYAPP");
// Will look for MYAPP_* environment variables
Source

pub fn separator(self, sep: impl Into<String>) -> Self

Set the separator used between prefix and field names.

The default separator is "_". This affects how environment variable names are constructed from the prefix and field names.

§Examples
use gonfig::Environment;

let env = Environment::new()
    .with_prefix("APP")
    .separator("__");  // Results in APP__FIELD_NAME
Source

pub fn case_sensitive(self, sensitive: bool) -> Self

Control case sensitivity for environment variable names.

When false (default), all environment variable names are converted to uppercase. When true, the exact case is preserved.

§Examples
use gonfig::Environment;

let env = Environment::new()
    .with_prefix("app")
    .case_sensitive(true);
// Will look for app_field_name instead of APP_FIELD_NAME
Source

pub fn override_with( self, key: impl Into<String>, value: impl Into<String>, ) -> Self

Override a specific field with a hardcoded value.

This is useful for providing default values or overriding environment variables programmatically. Overrides take precedence over actual environment variables.

§Examples
use gonfig::Environment;

let env = Environment::new()
    .override_with("debug", "true")
    .override_with("timeout", "30");
Source

pub fn with_field_mapping( self, field_name: impl Into<String>, env_key: impl Into<String>, ) -> Self

Map a specific field to a custom environment variable name.

This allows you to override the default environment variable naming for specific fields. The mapping takes precedence over the standard prefix and separator rules.

§Examples
use gonfig::Environment;

let env = Environment::new()
    .with_prefix("APP")
    .with_field_mapping("database_url", "DATABASE_CONNECTION_STRING");
// database_url will read from DATABASE_CONNECTION_STRING instead of APP_DATABASE_URL
Source

pub fn nested(self, nested: bool) -> Self

Enable nested mode to convert flat environment variable keys into nested structures.

When enabled, environment variables with the configured separator (default: _) will be split into nested paths. For example, APP_HTTP_PORT=9000 becomes {"http": {"port": 9000}}.

This is essential for properly overriding nested configuration file values with environment variables when using the Deep merge strategy.

§Examples
use gonfig::{Environment, ConfigBuilder, MergeStrategy};

// With nested=true, APP_HTTP_PORT will override http.port in config file
let env = Environment::new()
    .with_prefix("APP")
    .nested(true);
Source

pub fn collect_for_struct( &self, struct_name: &str, fields: &[(&str, Option<&str>)], ) -> HashMap<String, Value>

Source

pub fn collect_with_flat_keys(&self) -> Result<Value>

Trait Implementations§

Source§

impl Clone for Environment

Source§

fn clone(&self) -> Environment

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl ConfigSource for Environment

Source§

fn source_type(&self) -> Source

Source§

fn collect(&self) -> Result<Value>

Source§

fn has_value(&self, key: &str) -> bool

Source§

fn get_value(&self, key: &str) -> Option<Value>

Source§

fn as_any(&self) -> &dyn Any

Source§

impl Debug for Environment

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Environment

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more