### Quick Start Configuration Source: https://github.com/nniel-ape/gonfig/blob/main/README.md Example of defining a configuration struct and loading it using environment variables, files, and flags. ```go package main import ( "fmt" "log" "os" "github.com/nniel-ape/gonfig" ) type Config struct { DB struct { Host string `default:"localhost" description:"database host" validate:"required"` Port int `default:"5432" description:"database port" validate:"min=1,max=65535"` } LogLevel string `default:"info" description:"logging level" validate:"oneof=debug info warn error"` Debug bool `default:"false" description:"enable debug mode"` } func main() { var cfg Config err := gonfig.Load(&cfg, gonfig.WithEnvPrefix("APP"), gonfig.WithFile("config.yaml"), gonfig.WithFlags(os.Args[1:]), ) if err != nil { log.Fatal(err) } fmt.Printf("Connecting to %s:%d\n", cfg.DB.Host, cfg.DB.Port) } ``` -------------------------------- ### Run basic gonfig example Source: https://github.com/nniel-ape/gonfig/blob/main/examples/README.md Executes the simplest usage example using default configurations. ```bash go run ./examples/01-basic ``` -------------------------------- ### Run gonfig examples via CLI Source: https://github.com/nniel-ape/gonfig/blob/main/examples/README.md Commands to execute various gonfig feature demonstrations from the repository root. ```bash go run ./examples/01-basic ``` ```bash cd examples/02-config-file && go run . ``` ```bash APP_LOG_LEVEL=warn go run ./examples/03-all-sources -- --server-port 9090 ``` ```bash go run ./examples/04-validation ``` ```bash cd examples/05-advanced-types && go run . ``` ```bash cd examples/06-manual-handling && go run . --help ``` ```bash cd examples/06-manual-handling && go run . --server-port 0 ``` -------------------------------- ### Configuration File Formats Source: https://github.com/nniel-ape/gonfig/blob/main/README.md Examples of configuration files in YAML, TOML, and JSON formats. ```yaml db: host: myhost port: 3306 log_level: debug ``` ```toml log_level = "debug" [db] host = "myhost" port = 3306 ``` ```json { "db": {"host": "myhost", "port": 3306}, "log_level": "debug" } ``` -------------------------------- ### Install gonfig Source: https://github.com/nniel-ape/gonfig/blob/main/README.md Command to add the gonfig package to your Go project. ```bash go get github.com/nniel-ape/gonfig ``` -------------------------------- ### Validation Rules Example Source: https://github.com/nniel-ape/gonfig/blob/main/README.md Specifies validation rules using the 'validate' struct tag. Rules like 'required', 'min=N', 'max=N', and 'oneof' can be applied to different types. All validation errors are collected and returned in a ValidationError. ```go validate:"required" ``` ```go validate:"min=1" ``` ```go validate:"max=65535" ``` ```go validate:"oneof=debug info warn error" ``` -------------------------------- ### Gonfig Error Types Source: https://github.com/nniel-ape/gonfig/blob/main/README.md Lists the common error types returned by Gonfig and provides examples of how to handle them using `errors.Is` and `errors.As`. ```APIDOC ## Error Types ### Description Common error types returned by Gonfig functions. ### Error Types - **`gonfig.ErrInvalidTarget`**: The target provided is not a non-nil pointer to a struct. - **`gonfig.ErrFileNotFound`**: A specified configuration file does not exist. - **`gonfig.ErrParse`**: A type conversion failed during configuration loading. - **`gonfig.ErrValidation`**: Validation failed. This error can be unwrapped to a `*gonfig.ValidationError` for detailed information. ### Error Handling Example ```go import ( "errors" "fmt" "your_project/gonfig" ) // Assuming 'err' is the error returned from a gonfig function var ve *gonfig.ValidationError if errors.As(err, &ve) { fmt.Println("Validation Errors:") for _, fe := range ve.Errors { fmt.Printf(" %s: %s\n", fe.Field, fe.Message) } } ``` ``` -------------------------------- ### Generate Help Text with Usage Source: https://context7.com/nniel-ape/gonfig/llms.txt Generates formatted help documentation from struct metadata, including flag names, environment variables, and default values. ```go package main import ( "fmt" "github.com/nniel-ape/gonfig" ) type Config struct { AppName string `default:"my-app" description:"application name"` LogLevel string `default:"info" description:"logging level" short:"l"` Server struct { Host string `default:"localhost" description:"server bind address" short:"H"` Port int `default:"8080" description:"server port" short:"p"` } Database struct { Host string `default:"localhost" description:"database host"` Port int `default:"5432" description:"database port"` Name string `default:"mydb" description:"database name"` User string `default:"postgres" description:"database user"` Password string `default:"" description:"database password"` } } func main() { var cfg Config usage := gonfig.Usage(&cfg, gonfig.WithEnvPrefix("APP")) fmt.Println(usage) } ``` -------------------------------- ### Gonfig Options for Loading Source: https://github.com/nniel-ape/gonfig/blob/main/README.md Provides various options to configure the loading process, such as specifying config files, environment variable prefixes, command-line flags, and content from bytes. Use multiple WithFile calls to load files in order, where later files override earlier ones. ```go gonfig.WithFile("config.yaml") ``` ```go gonfig.WithEnvPrefix("APP") ``` ```go gonfig.WithFlags(os.Args[1:]) ``` ```go gonfig.WithFileContent(data, gonfig.JSON) ``` ```go gonfig.WithAutoHelp(false) ``` ```go gonfig.WithoutValidation() ``` -------------------------------- ### Define Configuration Struct and Load Source: https://github.com/nniel-ape/gonfig/blob/main/docs/plans/completed/2026-03-15-gonfig-multi-source-config-library.md Use struct tags to define default values, descriptions, and validation rules. The Load function merges sources based on the defined priority. ```go type Config struct { DB struct { Host string `default:"localhost" description:"database host" validate:"required"` Port int `default:"5432" description:"database port" validate:"min=1,max=65535"` Password string `default:"" description:"database password"` } LogLevel string `default:"info" description:"logging level" validate:"oneof=debug info warn error"` Debug bool `default:"false" description:"enable debug mode"` } var cfg Config err := gonfig.Load(&cfg, gonfig.WithEnvPrefix("APP"), gonfig.WithFile("config.yaml"), gonfig.WithFlags(os.Args[1:]), ) ``` -------------------------------- ### Generate Usage Help Text Source: https://github.com/nniel-ape/gonfig/blob/main/README.md Generates formatted help text for configuration fields, including flag names, environment variable names, types, defaults, and descriptions. Fields are organized by nested struct sections. ```go func Usage(target any, opts ...Option) string ``` -------------------------------- ### Load Configuration from Files Source: https://context7.com/nniel-ape/gonfig/llms.txt The WithFile option supports loading from JSON, YAML, or TOML files. Chaining multiple WithFile calls allows for layered configuration where later files override values from earlier ones. ```go package main import ( "fmt" "log" "github.com/nniel-ape/gonfig" ) type Config struct { Server struct { Host string `default:"localhost"` Port int `default:"8080"` Password string `default:""` } Database struct { Host string `default:"localhost"` Port int `default:"5432"` Name string `default:"mydb"` User string `default:"postgres"` } LogLevel string `default:"info"` } func main() { var cfg Config // Load base config, then override with environment-specific config err := gonfig.Load(&cfg, gonfig.WithFile("config.yaml"), // Base configuration gonfig.WithFile("config.production.yaml"), // Environment overrides (later wins) ) if err != nil { log.Fatal(err) } fmt.Printf("Server: %s:%d\n", cfg.Server.Host, cfg.Server.Port) fmt.Printf("Database: %s@%s:%d/%s\n", cfg.Database.User, cfg.Database.Host, cfg.Database.Port, cfg.Database.Name) fmt.Printf("LogLevel: %s\n", cfg.LogLevel) } ``` -------------------------------- ### Load Configuration Function Source: https://github.com/nniel-ape/gonfig/blob/main/README.md Populates the target struct from all configured sources. The target must be a non-nil pointer to a struct. ```go func Load(target any, opts ...Option) error ``` -------------------------------- ### Load Configuration from Multiple Sources Source: https://context7.com/nniel-ape/gonfig/llms.txt The Load function populates a target struct using defaults, files, environment variables, and flags in priority order. It requires a pointer to a struct and returns an error if validation or type conversion fails. ```go package main import ( "fmt" "log" "os" "github.com/nniel-ape/gonfig" ) type Config struct { Server struct { Host string `default:"localhost" description:"server bind address"` Port int `default:"8080" description:"server port" validate:"min=1,max=65535"` } Database struct { Host string `default:"localhost" description:"database host"` Port int `default:"5432" description:"database port"` Name string `default:"mydb" description:"database name" validate:"required"` } LogLevel string `default:"info" description:"logging level" validate:"oneof=debug info warn error"` } func main() { var cfg Config err := gonfig.Load(&cfg, gonfig.WithFile("config.yaml"), // Load from YAML file gonfig.WithEnvPrefix("APP"), // Env vars: APP_SERVER_HOST, APP_LOG_LEVEL, etc. gonfig.WithFlags(os.Args[1:]), // Parse CLI flags: --server-port, --log-level, etc. ) if err != nil { log.Fatal(err) } fmt.Printf("Server: %s:%d\n", cfg.Server.Host, cfg.Server.Port) fmt.Printf("Database: %s:%d/%s\n", cfg.Database.Host, cfg.Database.Port, cfg.Database.Name) fmt.Printf("LogLevel: %s\n", cfg.LogLevel) } ``` -------------------------------- ### Handle --help Manually with WithAutoHelp(false) Source: https://context7.com/nniel-ape/gonfig/llms.txt Disables automatic help printing, returning flag.ErrHelp for custom handling. Useful for custom banners or integrating with CLI frameworks. Requires manual printing of usage information. ```go package main import ( "errors" "flag" "fmt" "os" "github.com/nniel-ape/gonfig" ) type Config struct { Server struct { Host string `default:"localhost" description:"server bind address" short:"H"` Port int `default:"8080" description:"server port" validate:"min=1,max=65535" short:"p"` } LogLevel string `default:"info" description:"logging level" validate:"oneof=debug info warn error" short:"l"` } func main() { var cfg Config err := gonfig.Load(&cfg, gonfig.WithEnvPrefix("APP"), gonfig.WithFlags(os.Args[1:]), gonfig.WithAutoHelp(false), // Disable auto-help ) // Handle --help manually if errors.Is(err, flag.ErrHelp) { fmt.Println("My Application v1.0.0") fmt.Println("A sample application demonstrating gonfig") fmt.Println() fmt.Println("Usage: myapp [flags]") fmt.Println() fmt.Print(gonfig.Usage(&cfg, gonfig.WithEnvPrefix("APP"))) os.Exit(0) } // Handle validation errors var ve *gonfig.ValidationError if errors.As(err, &ve) { fmt.Fprintln(os.Stderr, "Configuration errors:") for _, fe := range ve.Errors { fmt.Fprintf(os.Stderr, " - %s: %s\n", fe.Field, fe.Message) } os.Exit(1) } if err != nil { fmt.Fprintln(os.Stderr, "Error:", err) os.Exit(1) } fmt.Printf("Server: %s:%d\n", cfg.Server.Host, cfg.Server.Port) fmt.Printf("LogLevel: %s\n", cfg.LogLevel) } ``` -------------------------------- ### Load Configuration from Bytes with WithFileContent Source: https://context7.com/nniel-ape/gonfig/llms.txt Use WithFileContent to load configuration data directly from memory, supporting JSON, YAML, or TOML formats. ```go package main import ( "fmt" "log" "github.com/nniel-ape/gonfig" ) type Config struct { AppName string `default:"my-app"` Port int `default:"8080"` Debug bool `default:"false"` LogLevel string `default:"info"` } func main() { var cfg Config // Embed configuration directly in code (useful for tests) configData := []byte(`{ "app_name": "test-service", "port": 9000, "debug": true, "log_level": "debug" }`) err := gonfig.Load(&cfg, gonfig.WithFileContent(configData, gonfig.JSON), ) if err != nil { log.Fatal(err) } fmt.Printf("AppName: %s\n", cfg.AppName) // Output: test-service fmt.Printf("Port: %d\n", cfg.Port) // Output: 9000 fmt.Printf("Debug: %t\n", cfg.Debug) // Output: true fmt.Printf("LogLevel: %s\n", cfg.LogLevel) // Output: debug } ``` -------------------------------- ### Load Advanced Types from Configuration Source: https://context7.com/nniel-ape/gonfig/llms.txt Configure slices, maps, and time.Duration fields using gonfig.Load with a file source. ```go package main import ( "fmt" "log" "time" "github.com/nniel-ape/gonfig" ) type Config struct { Server struct { Host string `default:"localhost" description:"server host"` Port int `default:"8080" description:"server port"` ReadTimeout time.Duration `default:"30s" description:"read timeout"` WriteTimeout time.Duration `default:"30s" description:"write timeout"` } AllowedOrigins []string `description:"CORS allowed origins"` RateLimits []int `description:"rate limit tiers (req/min)"` Weights []float64 `description:"load balancer weights"` Labels map[string]string `description:"metadata labels"` } func main() { var cfg Config if err := gonfig.Load(&cfg, gonfig.WithFile("config.yaml")); err != nil { log.Fatal(err) } fmt.Printf("Server Host: %s\n", cfg.Server.Host) fmt.Printf("Server Port: %d\n", cfg.Server.Port) fmt.Printf("ReadTimeout: %s\n", cfg.Server.ReadTimeout) fmt.Printf("WriteTimeout: %s\n", cfg.Server.WriteTimeout) fmt.Printf("AllowedOrigins: %v\n", cfg.AllowedOrigins) fmt.Printf("RateLimits: %v\n", cfg.RateLimits) fmt.Printf("Weights: %v\n", cfg.Weights) fmt.Printf("Labels: %v\n", cfg.Labels) } ``` -------------------------------- ### Gonfig Usage API Source: https://github.com/nniel-ape/gonfig/blob/main/README.md The `Usage` function generates formatted help text for the configuration, detailing flag names, environment variable names, types, defaults, and descriptions. ```APIDOC ## Usage ### Description Generates formatted help text showing flag names, env var names, types, defaults, and descriptions. Fields are grouped by nested struct sections. ### Function Signature ```go func Usage(target any, opts ...Option) string ``` ### Parameters - **target** (any) - Required - A non-nil pointer to a struct representing the configuration structure. - **opts** (...Option) - Optional - Configuration options that might influence the help text generation. ``` -------------------------------- ### Gonfig Options Source: https://github.com/nniel-ape/gonfig/blob/main/README.md Various options can be passed to `Load` to customize its behavior, such as specifying configuration files, environment variable prefixes, command-line flags, and more. ```APIDOC ## Options ### Description Options to customize the configuration loading process. ### Available Options - **`gonfig.WithFile(filePath string)`**: Load configuration from a file. The format is detected by the file extension (e.g., `.yaml`, `.json`, `.toml`). Multiple `WithFile` calls load files in order, with later files overriding earlier ones. - **`gonfig.WithEnvPrefix(prefix string)`**: Set a prefix for environment variable lookups. Only environment variables starting with this prefix will be considered. - **`gonfig.WithFlags(args []string)`**: Parse command-line flags from the provided string slice. Typically `os.Args[1:]` is used. - **`gonfig.WithFileContent(data []byte, format string)`**: Load configuration directly from a byte slice. Useful for testing or embedding configuration data. The `format` parameter specifies the content type (e.g., `gonfig.JSON`, `gonfig.YAML`). - **`gonfig.WithAutoHelp(enable bool)`**: Control automatic help message display. If `true` (default when `WithFlags` is used), passing `--help` or `-h` will print usage and exit. If `false`, `Load` returns `flag.ErrHelp` for manual handling. - **`gonfig.WithoutValidation()`**: Skip the validation step after loading configuration. This is useful if custom validation logic is implemented elsewhere. ``` -------------------------------- ### Load Configuration Source: https://github.com/nniel-ape/gonfig/blob/main/llms.txt The Load function is the primary entry point for populating a configuration struct from various sources. ```APIDOC ## Load(target interface{}, options ...Option) error ### Description Populates a struct pointer from all configured sources (environment variables, command-line flags, config files, and defaults). ### Parameters - **target** (interface{}) - Required - A pointer to the configuration struct to be populated. - **options** (...Option) - Optional - Functional options to customize loading behavior (e.g., WithFile, WithEnvPrefix, WithFlags). ``` -------------------------------- ### Handle Specific Errors with errors.Is and errors.As Source: https://context7.com/nniel-ape/gonfig/llms.txt Demonstrates handling various gonfig errors like ErrFileNotFound, ErrInvalidTarget, ErrParse, and ErrValidation. Use errors.Is for sentinel errors and errors.As for structured errors like ValidationError. ```go package main import ( "errors" "fmt" "os" "github.com/nniel-ape/gonfig" ) type Config struct { Port int `default:"8080" validate:"required,min=1,max=65535"` } func main() { var cfg Config err := gonfig.Load(&cfg, gonfig.WithFile("nonexistent.yaml")) // Check for specific error types switch { case errors.Is(err, gonfig.ErrFileNotFound): fmt.Println("Config file not found, using defaults") // Retry without file err = gonfig.Load(&cfg) case errors.Is(err, gonfig.ErrInvalidTarget): fmt.Println("Invalid target: must be pointer to struct") os.Exit(1) case errors.Is(err, gonfig.ErrParse): fmt.Println("Failed to parse configuration value") os.Exit(1) case errors.Is(err, gonfig.ErrValidation): var ve *gonfig.ValidationError if errors.As(err, &ve) { fmt.Println("Validation errors:") for _, fe := range ve.Errors { fmt.Printf(" %s: %s\n", fe.Field, fe.Message) } } os.Exit(1) } if err != nil { fmt.Println("Unexpected error:", err) os.Exit(1) } fmt.Printf("Port: %d\n", cfg.Port) } ``` -------------------------------- ### Run All Tests Source: https://github.com/nniel-ape/gonfig/blob/main/CLAUDE.md Execute all tests within the project. Use this for a comprehensive test run. ```bash go test ./... ``` -------------------------------- ### Configuration File Formats Source: https://github.com/nniel-ape/gonfig/blob/main/docs/plans/completed/2026-03-15-gonfig-multi-source-config-library.md Supported file formats that map to the same configuration struct. ```yaml # config.yaml db: host: myhost port: 3306 log_level: debug ``` ```toml # config.toml log_level = "debug" [db] host = "myhost" port = 3306 ``` ```json { "db": {"host": "myhost", "port": 3306}, "log_level": "debug" } ``` -------------------------------- ### Run Tests with Coverage Summary Source: https://github.com/nniel-ape/gonfig/blob/main/CLAUDE.md Execute tests and display a summary of code coverage. Helps identify untested code sections. ```bash go test -cover ./... ``` -------------------------------- ### Usage Help Generation Source: https://github.com/nniel-ape/gonfig/blob/main/llms.txt The Usage function generates formatted help text based on the struct metadata. ```APIDOC ## Usage(target interface{}) string ### Description Generates aligned columnar help text grouped by struct sections, useful for CLI applications. ### Parameters - **target** (interface{}) - Required - The configuration struct to generate help text for. ``` -------------------------------- ### WithFile Option Source: https://context7.com/nniel-ape/gonfig/llms.txt The WithFile option specifies a configuration file path to load, with automatic format detection. ```APIDOC ## WithFile(path string) ### Description Adds a configuration file path to the loading process. Supported formats are JSON, YAML, and TOML, detected by file extension. ### Parameters #### Path Parameters - **path** (string) - Required - The file path to the configuration file. ``` -------------------------------- ### Gonfig Load API Source: https://github.com/nniel-ape/gonfig/blob/main/README.md The `Load` function populates a target struct from various configuration sources based on priority. The target must be a non-nil pointer to a struct. ```APIDOC ## Load ### Description Populates the target struct from all configured sources. The target must be a non-nil pointer to a struct. ### Function Signature ```go func Load(target any, opts ...Option) error ``` ### Parameters - **target** (any) - Required - A non-nil pointer to a struct to be populated. - **opts** (...Option) - Optional - Configuration options for loading. ``` -------------------------------- ### Error Type Matching with errors.Is/As Source: https://github.com/nniel-ape/gonfig/blob/main/README.md Demonstrates how to use `errors.Is` and `errors.As` to match specific error types returned by Gonfig. This is useful for handling validation errors and inspecting their details. ```go var ve *gonfig.ValidationError if errors.As(err, &ve) { for _, fe := range ve.Errors { fmt.Printf(" %s: %s\n", fe.Field, fe.Message) } } ``` -------------------------------- ### Generate HTML Coverage Report Source: https://github.com/nniel-ape/gonfig/blob/main/CLAUDE.md Generate a coverage profile and open it as an HTML report. Provides detailed insights into test coverage. ```bash go test -coverprofile=coverage.out ./... && go tool cover -html=coverage.out ``` -------------------------------- ### Gonfig Supported Types Source: https://github.com/nniel-ape/gonfig/blob/main/README.md Details the Go types supported by Gonfig and how they are handled when loaded from environment variables (as strings) or configuration files (native types). ```APIDOC ## Supported Types ### Description Mapping of Go types to their representation and parsing in environment variables and configuration files. | Go Type | Env/Flag (string) | File (native) | |---------------------|-------------------|---------------------| | `string` | as-is | `string` | | `int`, `int64` | parsed | `float64` → int | | `float64` | parsed | `float64` | | `bool` | parsed | `bool` | | `time.Duration` | `time.ParseDuration` | `string` → parse | | `[]string` | comma-separated | native array | | `[]int` | comma-separated | native array | | `[]float64` | comma-separated | native array | | `map[string]string` | not supported | native map | | `map[string]any` | not supported | native map | ``` -------------------------------- ### Package Structure Source: https://github.com/nniel-ape/gonfig/blob/main/docs/plans/completed/2026-03-15-gonfig-multi-source-config-library.md The gonfig package is organized into several Go files, each responsible for a specific aspect of configuration loading, validation, and usage generation. Test files are co-located with their respective implementation files. ```go gonfig/ ├── gonfig.go # Load(), Option types, public API ├── gonfig_test.go # Integration/end-to-end tests ├── field.go # fieldInfo, extractFields, name derivation ├── field_test.go ├── value.go # setFieldValue, type conversion ├── value_test.go ├── defaults.go # applyDefaults ├── defaults_test.go ├── file.go # loadFile, decodeJSON/YAML/TOML, applyMap ├── file_test.go ├── env.go # applyEnv ├── env_test.go ├── flag.go # applyFlags ├── flag_test.go ├── validate.go # validate, ValidationError ├── validate_test.go ├── usage.go # Usage() ├── usage_test.go ├── testdata/ │ ├── valid.json │ ├── valid.yaml │ ├── valid.toml │ ├── nested.json │ ├── nested.yaml │ ├── nested.toml │ ├── empty.json │ └── invalid.json ├── go.mod ├── go.sum └── README.md ``` -------------------------------- ### Validate Configuration Structs Source: https://context7.com/nniel-ape/gonfig/llms.txt Use the validate struct tag to enforce constraints and handle errors using errors.Is and errors.As. ```go package main import ( "errors" "fmt" "os" "github.com/nniel-ape/gonfig" ) type Config struct { Port int `default:"0" validate:"required,min=1,max=65535" description:"listen port"` Environment string `default:"staging" validate:"oneof=development production" description:"app environment"` Workers int `default:"100" validate:"min=1,max=16" description:"number of workers"` Name string `default:"" validate:"required" description:"application name"` } func main() { var cfg Config err := gonfig.Load(&cfg) // Check if error is a validation error using errors.Is if errors.Is(err, gonfig.ErrValidation) { fmt.Println("Validation failed!") } // Extract structured ValidationError using errors.As var ve *gonfig.ValidationError if errors.As(err, &ve) { fmt.Printf("Found %d validation error(s):\n\n", len(ve.Errors)) for i, fe := range ve.Errors { fmt.Printf("%d. Field: %s\n", i+1, fe.Field) fmt.Printf(" Rule: %s\n", fe.Rule) fmt.Printf(" Message: %s\n\n", fe.Message) } os.Exit(1) } if err != nil { fmt.Println("unexpected error:", err) os.Exit(1) } fmt.Println("Config is valid!") } ``` -------------------------------- ### Set Environment Variable Prefix with WithEnvPrefix Source: https://context7.com/nniel-ape/gonfig/llms.txt Use WithEnvPrefix to define a namespace for environment variables, preventing naming collisions. ```go package main import ( "fmt" "log" "os" "github.com/nniel-ape/gonfig" ) type Config struct { DB struct { Host string `default:"localhost" description:"database host"` Port int `default:"5432" description:"database port"` User string `default:"postgres" description:"database user"` Password string `default:"" description:"database password"` } LogLevel string `default:"info" description:"logging level"` Debug bool `default:"false" description:"enable debug mode"` } func main() { // Set environment variables (typically done outside the app) os.Setenv("MYAPP_DB_HOST", "prod-db.example.com") os.Setenv("MYAPP_DB_PORT", "5433") os.Setenv("MYAPP_DB_PASSWORD", "secret123") os.Setenv("MYAPP_LOG_LEVEL", "warn") var cfg Config err := gonfig.Load(&cfg, gonfig.WithEnvPrefix("MYAPP"), // All env vars prefixed with MYAPP_ ) if err != nil { log.Fatal(err) } fmt.Printf("DB.Host: %s\n", cfg.DB.Host) // Output: prod-db.example.com fmt.Printf("DB.Port: %d\n", cfg.DB.Port) // Output: 5433 fmt.Printf("DB.User: %s\n", cfg.DB.User) // Output: postgres (default) fmt.Printf("DB.Password: %s\n", cfg.DB.Password) // Output: secret123 fmt.Printf("LogLevel: %s\n", cfg.LogLevel) // Output: warn fmt.Printf("Debug: %t\n", cfg.Debug) // Output: false (default) } ``` -------------------------------- ### Parse Command-Line Flags with WithFlags Source: https://context7.com/nniel-ape/gonfig/llms.txt Enables parsing of command-line arguments into a configuration struct. Flag names are automatically derived from struct field paths. ```go package main import ( "fmt" "log" "os" "github.com/nniel-ape/gonfig" ) type Config struct { Server struct { Host string `default:"localhost" description:"server bind address" short:"H"` Port int `default:"8080" description:"server port" short:"p"` } Database struct { Host string `default:"localhost" description:"database host"` Port int `default:"5432" description:"database port"` Name string `default:"mydb" description:"database name" validate:"required"` } LogLevel string `default:"info" description:"logging level" short:"l"` Debug bool `default:"false" description:"enable debug mode" short:"d"` } func main() { var cfg Config err := gonfig.Load(&cfg, gonfig.WithFlags(os.Args[1:]), // Parse CLI flags ) if err != nil { log.Fatal(err) } fmt.Printf("Server: %s:%d\n", cfg.Server.Host, cfg.Server.Port) fmt.Printf("Database: %s:%d/%s\n", cfg.Database.Host, cfg.Database.Port, cfg.Database.Name) fmt.Printf("LogLevel: %s\n", cfg.LogLevel) fmt.Printf("Debug: %t\n", cfg.Debug) } ``` -------------------------------- ### Run Tests Verbose and Without Cache Source: https://github.com/nniel-ape/gonfig/blob/main/CLAUDE.md Run tests with verbose output and disable the test cache for fresh results. Useful for CI or when suspecting caching issues. ```bash go test -v -count=1 ./... ``` -------------------------------- ### Gonfig Validation Rules Source: https://github.com/nniel-ape/gonfig/blob/main/README.md Defines how to specify validation rules using the `validate` struct tag, including required fields, minimum/maximum values, and allowed values. ```APIDOC ## Validation Rules ### Description Rules are specified in the `validate` tag, comma-separated. ### Supported Rules | Rule | Applies to | Example | |-------------|---------------|-------------------------| | `required` | All types | `validate:"required"` | | `min=N` | Numeric types | `validate:"min=1"` | | `max=N` | Numeric types | `validate:"max=65535"` | | `oneof=a b c` | All types | `validate:"oneof=debug info warn error"` | All validation errors are collected and returned together in a `ValidationError`. ``` -------------------------------- ### Run Specific Test Source: https://github.com/nniel-ape/gonfig/blob/main/CLAUDE.md Execute a single test case by its name. Useful for targeted debugging. ```bash go test -run TestName ./... ``` -------------------------------- ### Gonfig Error Types Source: https://github.com/nniel-ape/gonfig/blob/main/README.md Lists common error types returned by Gonfig, including invalid target, file not found, parse errors, and validation failures. Use `errors.Is` and `errors.As` for error handling. ```go gonfig.ErrInvalidTarget ``` ```go gonfig.ErrFileNotFound ``` ```go gonfig.ErrParse ``` ```go gonfig.ErrValidation ``` -------------------------------- ### Struct-Level gonfig Tag Source: https://github.com/nniel-ape/gonfig/blob/main/README.md Using the gonfig tag on a struct field to override the path segment for all child fields. ```go type Config struct { Strategy Strategy `gonfig:"latemomentum"` } type Strategy struct { Name string Weight float64 } // Strategy.Name → env LATEMOMENTUM_NAME, flag --latemomentum-name, config key latemomentum.name // Strategy.Weight → env LATEMOMENTUM_WEIGHT, flag --latemomentum-weight, config key latemomentum.weight ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.