### Set environment variables for quick start Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/README.md Examples of setting variables for local development versus production environments. ```bash export API_KEY=dev-key-123 export PORT=3000 ``` ```bash export API_KEY_FILE=/run/secrets/api-key export PORT=8080 ``` -------------------------------- ### Quick start configuration loading Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/README.md Derive ServiceConf on a struct and use from_env() to populate fields from the environment. ```rust use serviceconf::ServiceConf; #[derive(Debug, ServiceConf)] struct Config { #[conf(from_file)] pub api_key: String, #[conf(default = 8080)] pub port: u16, } fn main() { let config = Config::from_env().unwrap(); println!("Port: {}", config.port); } ``` -------------------------------- ### Install serviceconf dependency Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/README.md Add the crate to your Cargo.toml file. ```toml [dependencies] serviceconf = "0.2" # Or from GitHub #serviceconf = { git = "https://github.com/lambdalisue/rs-serviceconf" } ``` -------------------------------- ### Set environment variables with prefix Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/README.md Example of setting prefixed environment variables. ```bash export MYAPP_DATABASE_URL=postgres://localhost/db export MYAPP_API_KEY=secret123 ``` -------------------------------- ### Environment Variables for Custom Deserializers Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/README.md Set environment variables to provide input for the custom deserializers. This example shows JSON array and comma-separated formats. ```bash export TAGS='["prod","api","v2"]' export FEATURES=feature1,feature2,feature3 ``` -------------------------------- ### Configure Struct with Custom Deserializers Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/README.md Use the `#[conf(deserializer = "function")]` attribute to specify custom parsing logic for struct fields. This example shows JSON array, comma-separated, and TOML deserialization. ```rust @derive(ServiceConf) struct Config { // JSON array #[conf(deserializer = "serde_json::from_str")] pub tags: Vec, // Comma-separated #[conf(deserializer = "comma_separated")] pub features: Vec, // TOML (requires toml crate) #[conf(deserializer = "toml::from_str")] pub settings: MySettings, } ``` -------------------------------- ### Handle Configuration Errors in Rust Source: https://context7.com/lambdalisue/rs-serviceconf/llms.txt Illustrates how to catch and handle errors returned by from_env(), including missing variables, parsing errors, and file read failures. ```rust use serviceconf::ServiceConf; #[derive(Debug, ServiceConf)] struct Config { pub api_key: String, pub port: u16, #[conf(from_file)] pub secret: String, } fn main() { // Example 1: Missing required variable std::env::remove_var("API_KEY"); std::env::set_var("PORT", "8080"); std::env::set_var("SECRET", "test"); match Config::from_env() { Ok(config) => println!("Config: {:?}", config), Err(e) => eprintln!("Error: {}", e), // Output: Error: Environment variable 'API_KEY' is required but not set } // Example 2: Parse error std::env::set_var("API_KEY", "secret123"); std::env::set_var("PORT", "not_a_number"); match Config::from_env() { Ok(config) => println!("Config: {:?}", config), Err(e) => eprintln!("Error: {}", e), // Output: Error: Failed to parse environment variable 'PORT' as u16: invalid digit found in string } // Example 3: File read error std::env::set_var("PORT", "8080"); std::env::remove_var("SECRET"); std::env::set_var("SECRET_FILE", "/nonexistent/path/secret.txt"); match Config::from_env() { Ok(config) => println!("Config: {:?}", config), Err(e) => eprintln!("Error: {}", e), // Output: Error: Failed to read file '/nonexistent/path/secret.txt' for environment variable 'SECRET_FILE': No such file or directory } } ``` -------------------------------- ### Handle configuration loading errors Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/serviceconf/README.md The from_env method returns a Result that should be checked for errors during initialization. ```rust use serviceconf::ServiceConf; #[derive(ServiceConf)] struct Config { pub api_key: String, } match Config::from_env() { Ok(config) => println!("Config loaded successfully"), Err(e) => eprintln!("Failed to load config: {}", e), } ``` -------------------------------- ### Error Handling Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/serviceconf/README.md Illustrates how to handle potential errors during configuration loading using `Result`. ```APIDOC ## Error Handling ### Description The `from_env()` method returns a `Result` that can be handled appropriately. ### Code Example ```rust use serviceconf::ServiceConf; #[derive(ServiceConf)] struct Config { pub api_key: String, } match Config::from_env() { Ok(config) => println!("Config loaded successfully"), Err(e) => eprintln!("Failed to load config: {}", e), } ``` ### Example Error Messages - `Environment variable 'DATABASE_URL' is required but not set` - `Failed to parse environment variable 'PORT' as u16: invalid digit found in string` - `Failed to read file '/etc/secrets/key' for environment variable 'API_KEY_FILE': No such file or directory` ``` -------------------------------- ### Combine Prefix, Custom Name, and File Loading Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/README.md Demonstrates combining multiple attributes: `prefix` for environment variable naming, `name` to override the variable name, and `from_file` to load values from a file. The field is an `Option`. ```rust @derive(ServiceConf) #[conf(prefix = "APP_")] struct Config { // Combines: prefix + custom name + from_file + Option #[conf(name = "DB_URL")] #[conf(from_file)] pub database_url: Option, // Reads from APP_DB_URL or APP_DB_URL_FILE // Combines: prefix + default #[conf(default = 8080)] pub port: u16, // Reads from APP_PORT, defaults to 8080 } ``` -------------------------------- ### Load Configuration from Environment Variables Source: https://context7.com/lambdalisue/rs-serviceconf/llms.txt Use the `ServiceConf` derive macro to automatically implement `from_env()` for loading configuration from environment variables. Field names are converted to UPPER_SNAKE_CASE. ```rust use serviceconf::ServiceConf; #[derive(Debug, ServiceConf)] struct Config { pub api_key: String, // Reads from API_KEY (required) pub database_url: String, // Reads from DATABASE_URL (required) } fn main() -> anyhow::Result<()> { // Set environment variables std::env::set_var("API_KEY", "secret-key-123"); std::env::set_var("DATABASE_URL", "postgres://localhost/db"); // Load configuration let config = Config::from_env()?; println!("API Key: {}", config.api_key); println!("Database URL: {}", config.database_url); // Output: // API Key: secret-key-123 // Database URL: postgres://localhost/db Ok(()) } ``` -------------------------------- ### Define Configuration with ServiceConf Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/serviceconf/README.md Use the ServiceConf derive macro to define configuration structures with support for file-based secrets and default values. ```rust use serviceconf::ServiceConf; #[derive(Debug, ServiceConf)] struct Config { // File-based secret: reads from API_KEY or API_KEY_FILE #[conf(from_file)] pub api_key: String, // Default value if not set #[conf(default = 8080)] pub port: u16, } let config = Config::from_env().unwrap(); println!("Port: {}", config.port); ``` -------------------------------- ### Define configuration with file-based secrets Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/README.md Use the #[conf(from_file)] attribute to enable automatic loading from either an environment variable or a file path specified by an environment variable. ```rust use serviceconf::ServiceConf; #[derive(ServiceConf)] struct Config { #[conf(from_file)] pub api_key: String, // Reads from API_KEY or API_KEY_FILE #[conf(from_file)] pub database_password: String, } ``` -------------------------------- ### Handle Configuration Errors in Rust Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/README.md Use this pattern to gracefully handle errors when loading configuration from environment variables. It prints the configuration on success or an error message on failure. ```rust match Config::from_env() { Ok(config) => println!("Config: {:?}", config), Err(e) => eprintln!("Error: {}", e), } ``` -------------------------------- ### Set environment variables for local development Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/README.md Directly export environment variables for local testing without requiring file mounts. ```bash export API_KEY=dev-key-123 export DATABASE_PASSWORD=dev-password ``` -------------------------------- ### Define optional configuration fields Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/README.md Fields wrapped in Option will be set to None if the corresponding environment variable is not found. ```rust #[derive(ServiceConf)] struct Config { pub api_key: Option, // None if API_KEY not set } ``` -------------------------------- ### Combine Multiple Attributes in Rust Source: https://context7.com/lambdalisue/rs-serviceconf/llms.txt Demonstrates applying multiple configuration attributes to struct fields, including defaults, file-based loading, and custom deserialization. ```rust use serviceconf::ServiceConf; use std::collections::HashMap; use std::io::Write; use tempfile::NamedTempFile; #[derive(Debug, ServiceConf)] #[conf(prefix = "APP_")] struct Config { // Required field with prefix pub name: String, // APP_NAME // Optional field with prefix pub version: Option, // APP_VERSION // Default value with prefix #[conf(default = 8080)] pub port: u16, // APP_PORT // Custom name + from_file + prefix #[conf(name = "DB_URL", from_file)] pub database_url: String, // APP_DB_URL or APP_DB_URL_FILE // File-based secret + optional #[conf(from_file)] pub oauth_token: Option, // APP_OAUTH_TOKEN or APP_OAUTH_TOKEN_FILE // Custom deserializer + prefix #[conf(deserializer = "serde_json::from_str")] pub tags: Vec, // APP_TAGS (JSON) // Custom deserializer + optional #[conf(deserializer = "serde_json::from_str")] pub metadata: Option>, // APP_METADATA (JSON, optional) } fn main() -> anyhow::Result<()> { // Required fields std::env::set_var("APP_NAME", "my-application"); std::env::set_var("APP_TAGS", r#"["production","api"]"#); // File-based secret let mut db_url_file = NamedTempFile::new()?; writeln!(db_url_file, "postgres://user:pass@localhost/db")?; std::env::set_var("APP_DB_URL_FILE", db_url_file.path()); // Optional field set std::env::set_var("APP_VERSION", "1.0.0"); // APP_OAUTH_TOKEN not set - will be None // APP_METADATA not set - will be None let config = Config::from_env()?; println!("Name: {}", config.name); // my-application println!("Version: {:?}", config.version); // Some("1.0.0") println!("Port: {}", config.port); // 8080 (default) println!("Database URL: {}", config.database_url); // postgres://user:pass@localhost/db println!("OAuth Token: {:?}", config.oauth_token); // None println!("Tags: {:?}", config.tags); // ["production", "api"] println!("Metadata: {:?}", config.metadata); // None Ok(()) } ``` -------------------------------- ### Combine multiple configuration attributes Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/serviceconf/README.md Attributes can be stacked to define complex loading behaviors like prefixes and file-based overrides. ```rust use serviceconf::ServiceConf; #[derive(ServiceConf)] #[conf(prefix = "APP_")] struct Config { // Combines: prefix + custom name + from_file + Option #[conf(name = "DB_URL")] #[conf(from_file)] pub database_url: Option, // Reads from APP_DB_URL or APP_DB_URL_FILE // Combines: prefix + default #[conf(default = 8080)] pub port: u16, // Reads from APP_PORT, defaults to 8080 } ``` -------------------------------- ### Apply Environment Variable Prefixes Source: https://context7.com/lambdalisue/rs-serviceconf/llms.txt Use the #[conf(prefix = "...")] attribute on a struct to prepend a string to all generated environment variable names. ```rust use serviceconf::ServiceConf; #[derive(Debug, ServiceConf)] #[conf(prefix = "MYAPP_")] struct Config { pub database_url: String, // Reads from MYAPP_DATABASE_URL pub api_key: String, // Reads from MYAPP_API_KEY #[conf(default = 8080)] pub port: u16, // Reads from MYAPP_PORT #[conf(default)] pub debug: bool, // Reads from MYAPP_DEBUG } fn main() -> anyhow::Result<()> { // Set environment variables with prefix std::env::set_var("MYAPP_DATABASE_URL", "postgres://localhost/db"); std::env::set_var("MYAPP_API_KEY", "secret-key-123"); std::env::set_var("MYAPP_PORT", "3000"); let config = Config::from_env()?; println!("Database URL: {}", config.database_url); // postgres://localhost/db println!("API Key: {}", config.api_key); // secret-key-123 println!("Port: {}", config.port); // 3000 println!("Debug: {}", config.debug); // false Ok(()) } ``` -------------------------------- ### Custom Deserializers Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/README.md How to use custom functions or existing deserializers for complex configuration types. ```APIDOC ## Custom Deserializers ### Description Use `#[conf(deserializer = "function")]` to handle complex types or custom parsing logic for configuration fields. ### Example ```rust fn comma_separated(s: &str) -> Result, String> { Ok(s.split(',').map(|s| s.trim().to_string()).collect()) } #[derive(ServiceConf)] struct Config { #[conf(deserializer = "serde_json::from_str")] pub tags: Vec, #[conf(deserializer = "comma_separated")] pub features: Vec, #[conf(deserializer = "toml::from_str")] pub settings: MySettings, } ``` ``` -------------------------------- ### Combining Attributes Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/serviceconf/README.md Demonstrates how to combine multiple ServiceConf attributes for advanced configuration scenarios. ```APIDOC ## Combining Attributes ### Description Multiple attributes can be combined to create powerful configurations. ### Code Example ```rust use serviceconf::ServiceConf; #[derive(ServiceConf)] #[conf(prefix = "APP_")] struct Config { // Combines: prefix + custom name + from_file + Option #[conf(name = "DB_URL")] #[conf(from_file)] pub database_url: Option, // Reads from APP_DB_URL or APP_DB_URL_FILE // Combines: prefix + default #[conf(default = 8080)] pub port: u16, // Reads from APP_PORT, defaults to 8080 } ``` ### Invalid Combinations - `Option` + `#[conf(default)]` or `#[conf(default = value)]` → Option already defaults to None ``` -------------------------------- ### Handle optional fields Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/serviceconf/README.md Fields wrapped in Option will be set to None if the corresponding environment variable is missing. ```rust use serviceconf::ServiceConf; #[derive(ServiceConf)] struct Config { pub api_key: Option, // None if API_KEY not set pub max_retries: Option, // None if MAX_RETRIES not set } ``` -------------------------------- ### Set Default Values for Configuration Fields Source: https://context7.com/lambdalisue/rs-serviceconf/llms.txt Configure default values for environment variables using `#[conf(default)]` for `Default::default()` or `#[conf(default = value)]` for an explicit value. This is useful for optional settings or local development. ```rust use serviceconf::ServiceConf; #[derive(Debug, ServiceConf)] struct Config { pub app_name: String, // Required - error if not set #[conf(default = 8080)] pub port: u16, // Uses 8080 if PORT not set #[conf(default = "localhost".to_string())] pub host: String, // Uses "localhost" if HOST not set #[conf(default)] pub debug: bool, // Uses false (Default::default()) if DEBUG not set #[conf(default)] pub max_retries: u32, // Uses 0 (Default::default()) if not set } fn main() -> anyhow::Result<()> { // Only set the required field std::env::set_var("APP_NAME", "my-service"); // Optionally override defaults std::env::set_var("PORT", "3000"); let config = Config::from_env()?; println!("App Name: {}", config.app_name); // my-service println!("Port: {}", config.port); // 3000 (overridden) println!("Host: {}", config.host); // localhost (default) println!("Debug: {}", config.debug); // false (default) println!("Max Retries: {}", config.max_retries); // 0 (default) Ok(()) } ``` -------------------------------- ### Run Tests with Cargo Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/README.md Execute all tests defined in your Rust project using the Cargo test command. ```bash cargo test ``` -------------------------------- ### Type Behavior Summary Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/serviceconf/README.md A table summarizing the behavior of different types and attributes when environment variables are missing or set. ```APIDOC ## Type Behavior | Type | When Env Var Missing | When Env Var Set | |------|---------------------|------------------| | `T` (no attribute) | Error | Parsed with `FromStr` | | `T` + `#[conf(default)]` | `Default::default()` | Parsed with `FromStr` | | `T` + `#[conf(default = value)]` | Uses `value` | Parsed with `FromStr` | | `Option` | `None` | `Some(parsed_value)` | | `T` + `#[conf(deserializer = "fn")]` | Error | Parsed with custom function | ``` -------------------------------- ### Apply a prefix to environment variables Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/README.md Use the prefix attribute at the struct level to prepend a string to all environment variable lookups. ```rust #[derive(ServiceConf)] #[conf(prefix = "MYAPP_")] struct Config { pub database_url: String, // Reads from MYAPP_DATABASE_URL pub api_key: String, // Reads from MYAPP_API_KEY } ``` -------------------------------- ### JSON Deserialization for Nested Structs and HashMaps Source: https://context7.com/lambdalisue/rs-serviceconf/llms.txt Demonstrates using `serde_json::from_str` with the `Deserialize` trait for complex nested configuration structures like structs and HashMaps. This is suitable for configurations that are naturally represented as JSON objects. ```rust use serviceconf::ServiceConf; use serde::Deserialize; use std::collections::HashMap; #[derive(Debug, Deserialize)] struct DatabaseConfig { pub host: String, pub port: u16, pub username: String, } #[derive(Debug, ServiceConf)] struct Config { pub app_name: String, pub max_connections: u32, // Nested struct from JSON #[conf(deserializer = "serde_json::from_str")] pub database: DatabaseConfig, // HashMap from JSON #[conf(deserializer = "serde_json::from_str")] pub environment_vars: HashMap, } fn main() -> anyhow::Result<()> { std::env::set_var("APP_NAME", "my-application"); std::env::set_var("MAX_CONNECTIONS", "100"); std::env::set_var("DATABASE", r#"{"host":"localhost","port":5432,"username":"admin"}""#); std::env::set_var("ENVIRONMENT_VARS", r#"{"LOG_LEVEL":"debug","TIMEOUT":"30"}""#); let config = Config::from_env()?; println!("App Name: {}", config.app_name); println!("Max Connections: {}", config.max_connections); println!("Database Host: {}", config.database.host); // localhost println!("Database Port: {}", config.database.port); // 5432 println!("Database User: {}", config.database.username); // admin println!("Env Vars: {:?}", config.environment_vars); Ok(()) } ``` -------------------------------- ### Implement File-based Secrets in Rust Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/serviceconf/README.md Use the #[conf(from_file)] attribute to map environment variables to file-based secrets. ```rust use serviceconf::ServiceConf; #[derive(ServiceConf)] struct Config { #[conf(from_file)] pub api_key: String, #[conf(from_file)] pub database_password: String, } ``` -------------------------------- ### Optional Fields Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/serviceconf/README.md Use `Option` to define fields that may not be present in the environment. ```APIDOC ## Optional Fields ### Description Use `Option` for optional fields. Returns `None` if the environment variable is not set. ### Code Example ```rust use serviceconf::ServiceConf; #[derive(ServiceConf)] struct Config { pub api_key: Option, // None if API_KEY not set pub max_retries: Option, // None if MAX_RETRIES not set } ``` ``` -------------------------------- ### Define default values for configuration fields Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/README.md Use the default attribute to provide fallback values when environment variables are missing. ```rust #[derive(ServiceConf)] struct Config { #[conf(default = 8080)] pub port: u16, // 8080 if PORT not set #[conf(default = "localhost".to_string())] pub host: String, // "localhost" if HOST not set } ``` -------------------------------- ### rs-serviceconf Attribute Reference Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/README.md Overview of struct and field-level attributes used to configure environment variable mapping and parsing behavior. ```APIDOC ## Struct-level Attributes - **#[conf(prefix = "PREFIX_")]**: Adds a prefix to all environment variable names mapped from the struct fields. ## Field-level Attributes - **#[conf(name = "VAR")]**: Overrides the default environment variable name. - **#[conf(default)]**: Uses `Default::default()` if the environment variable is not set. - **#[conf(default = value)]**: Uses an explicit default value if the environment variable is not set. - **#[conf(from_file)]**: Supports the `{VAR}_FILE` pattern, useful for secrets stored in files. - **#[conf(deserializer = "fn")]**: Specifies a custom parser function for complex types like `Vec` or `HashMap`. ``` -------------------------------- ### Apply Struct-level Prefix Attribute Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/serviceconf/README.md Use the prefix attribute to automatically prepend a string to all environment variable lookups for the struct. ```rust use serviceconf::ServiceConf; #[derive(ServiceConf)] #[conf(prefix = "MYAPP_")] struct Config { pub database_url: String, // Reads from MYAPP_DATABASE_URL pub api_key: String, // Reads from MYAPP_DATABASE_KEY } ``` -------------------------------- ### Default Value Behavior Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/serviceconf/README.md Control how default values are handled when environment variables are not set. ```APIDOC ## `#[conf(default)]` ### Description Use `Default::default()` if the environment variable is not set. ### Code Example ```rust use serviceconf::ServiceConf; #[derive(ServiceConf)] struct Config { #[conf(default)] pub port: u16, // Uses 0 (u16::default()) if PORT not set #[conf(default)] pub host: String, // Uses "" (String::default()) if HOST not set } ``` ## `#[conf(default = value)]` ### Description Specify an explicit default value when the environment variable is not set. ### Code Example ```rust use serviceconf::ServiceConf; #[derive(ServiceConf)] struct Config { #[conf(default = "127.0.0.1:8080".to_string())] pub server_addr: String, #[conf(default = 10)] pub max_connections: u32, #[conf(default = false)] pub enable_tls: bool, } ``` ``` -------------------------------- ### Specify explicit default values Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/serviceconf/README.md Provide a specific value to use when the environment variable is not set. ```rust use serviceconf::ServiceConf; #[derive(ServiceConf)] struct Config { #[conf(default = "127.0.0.1:8080".to_string())] pub server_addr: String, #[conf(default = 10)] pub max_connections: u32, #[conf(default = false)] pub enable_tls: bool, } ``` -------------------------------- ### Configure Kubernetes Secrets for serviceconf Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/README.md Mount secrets as files in a Kubernetes deployment to be consumed by the application via file-based environment variables. ```yaml apiVersion: v1 kind: Secret metadata: name: app-secrets type: Opaque stringData: api-key: "prod-api-key-123" db-password: "secure-password" --- apiVersion: apps/v1 kind: Deployment metadata: name: myservice spec: template: spec: containers: - name: app image: myservice:latest env: - name: API_KEY_FILE value: /etc/secrets/api-key - name: DATABASE_PASSWORD_FILE value: /etc/secrets/db-password volumeMounts: - name: secrets mountPath: /etc/secrets readOnly: true volumes: - name: secrets secret: secretName: app-secrets items: - key: api-key path: api-key - key: db-password path: db-password ``` -------------------------------- ### Define Custom Deserializer Function Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/README.md Define a custom parser function that takes a string slice and returns a Result. This function will be used by the `ServiceConf` derive macro. ```rust // Custom parser fn comma_separated(s: &str) -> Result, String> { Ok(s.split(',').map(|s| s.trim().to_string()).collect()) } ``` -------------------------------- ### Define Field-level File-based Secret Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/serviceconf/README.md Apply the from_file attribute to a specific field to enable file-based secret loading. ```rust use serviceconf::ServiceConf; #[derive(ServiceConf)] pub struct Config { // Reads from API_KEY or API_KEY_FILE #[conf(from_file)] pub api_key: String, } ``` -------------------------------- ### Custom Environment Variable Name Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/serviceconf/README.md Use the `name` attribute to specify a different environment variable name than the field name. ```APIDOC ## `#[conf(name = "CUSTOM_NAME")]` ### Description Specify an environment variable name different from the field name. ### Code Example ```rust use serviceconf::ServiceConf; #[derive(ServiceConf)] pub struct Config { // Load from REDIS_URL environment variable #[conf(name = "REDIS_URL")] pub redis_connection_string: String, } ``` ``` -------------------------------- ### Custom Deserialization Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/serviceconf/README.md Use custom deserializer functions for complex types or specific parsing logic. ```APIDOC ## `#[conf(deserializer = "function")]` ### Description Use a custom deserializer function for complex types or custom parsing logic. The deserializer function must have the signature: ```rust,ignore fn deserialize(s: &str) -> Result ``` ### Example with JSON ```rust use serviceconf::ServiceConf; #[derive(ServiceConf)] struct Config { // Parse JSON array #[conf(deserializer = "serde_json::from_str")] pub tags: Vec, } ``` Environment variable: ```bash export TAGS='["prod","api","v2"]' ``` ### Example with custom function ```rust use serviceconf::ServiceConf; // Custom comma-separated parser fn comma_separated(s: &str) -> Result, String> { Ok(s.split(',').map(|s| s.trim().to_string()).collect()) } #[derive(ServiceConf)] struct Config { #[conf(deserializer = "comma_separated")] pub features: Vec, } ``` Environment variable: ```bash export FEATURES=feature1,feature2,feature3 ``` ``` -------------------------------- ### Customize environment variable name Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/serviceconf/README.md Use the name attribute to map a struct field to a specific environment variable name. ```rust use serviceconf::ServiceConf; #[derive(ServiceConf)] pub struct Config { // Load from REDIS_URL environment variable #[conf(name = "REDIS_URL")] pub redis_connection_string: String, } ``` -------------------------------- ### Custom deserialization for complex types Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/serviceconf/README.md Use the deserializer attribute to specify a function for parsing environment variables. ```rust use serviceconf::ServiceConf; #[derive(ServiceConf)] struct Config { // Parse JSON array #[conf(deserializer = "serde_json::from_str")] pub tags: Vec, } ``` ```bash export TAGS='["prod","api","v2"]' ``` ```rust use serviceconf::ServiceConf; // Custom comma-separated parser fn comma_separated(s: &str) -> Result, String> { Ok(s.split(',').map(|s| s.trim().to_string()).collect()) } #[derive(ServiceConf)] struct Config { #[conf(deserializer = "comma_separated")] pub features: Vec, } ``` ```bash export FEATURES=feature1,feature2,feature3 ``` -------------------------------- ### Custom Deserializer for Comma-Separated Strings Source: https://context7.com/lambdalisue/rs-serviceconf/llms.txt Defines a custom deserializer function `comma_separated` to parse comma-separated string values into a `Vec`. This is useful for configuration options that accept multiple values in a single string. ```rust use serviceconf::ServiceConf; use std::collections::HashMap; // Custom deserializer for comma-separated strings fn comma_separated(s: &str) -> Result, String> { Ok(s.split(',').map(|s| s.trim().to_string()).collect()) } #[derive(Debug, ServiceConf)] struct Config { pub app_name: String, // JSON array using serde_json #[conf(deserializer = "serde_json::from_str")] pub tags: Vec, // JSON object using serde_json #[conf(deserializer = "serde_json::from_str")] pub metadata: HashMap, // Custom comma-separated format #[conf(deserializer = "comma_separated")] pub features: Vec, // Deserializer with default value #[conf(deserializer = "comma_separated", default)] pub allowed_hosts: Vec, } fn main() -> anyhow::Result<()> { std::env::set_var("APP_NAME", "my-service"); std::env::set_var("TAGS", r#"["production","api","v2"]"#); std::env::set_var("METADATA", r#"{"version":"1.0","env":"prod"}""#); std::env::set_var("FEATURES", "auth, logging, metrics"); // ALLOWED_HOSTS not set - will use default empty Vec let config = Config::from_env()?; println!("App Name: {}", config.app_name); // my-service println!("Tags: {:?}", config.tags); // ["production", "api", "v2"] println!("Metadata: {:?}", config.metadata); // {"version": "1.0", "env": "prod"} println!("Features: {:?}", config.features); // ["auth", "logging", "metrics"] println!("Allowed Hosts: {:?}", config.allowed_hosts); // [] Ok(()) } ``` -------------------------------- ### Override environment variable names Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/README.md Use the name attribute to specify a custom environment variable name for a specific field. ```rust #[derive(ServiceConf)] struct Config { #[conf(name = "POSTGRES_URL")] pub database_url: String, // Reads from POSTGRES_URL, not DATABASE_URL } ``` -------------------------------- ### Use default values for missing variables Source: https://github.com/lambdalisue/rs-serviceconf/blob/main/serviceconf/README.md The default attribute uses the type's Default implementation if the environment variable is missing. ```rust use serviceconf::ServiceConf; #[derive(ServiceConf)] struct Config { #[conf(default)] pub port: u16, // Uses 0 (u16::default()) if PORT not set #[conf(default)] pub host: String, // Uses "" (String::default()) if HOST not set } ``` -------------------------------- ### Override Field Environment Variable Names Source: https://context7.com/lambdalisue/rs-serviceconf/llms.txt Use the #[conf(name = "...")] attribute to specify a custom environment variable name for a specific field, overriding the default naming convention. ```rust use serviceconf::ServiceConf; #[derive(Debug, ServiceConf)] #[conf(prefix = "APP_")] struct Config { // Uses custom name instead of auto-generated APP_DATABASE_URL #[conf(name = "DATABASE_CONNECTION_STRING")] pub database_url: String, // Reads from APP_DATABASE_CONNECTION_STRING #[conf(name = "POSTGRES_URL")] pub pg_connection: String, // Reads from APP_POSTGRES_URL pub api_key: String, // Uses default: APP_API_KEY } fn main() -> anyhow::Result<()> { std::env::set_var("APP_DATABASE_CONNECTION_STRING", "mysql://localhost/db"); std::env::set_var("APP_POSTGRES_URL", "postgres://localhost/pg"); std::env::set_var("APP_API_KEY", "secret123"); let config = Config::from_env()?; println!("Database URL: {}", config.database_url); // mysql://localhost/db println!("PG Connection: {}", config.pg_connection); // postgres://localhost/pg println!("API Key: {}", config.api_key); // secret123 Ok(()) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.