### Running Plugin System VCFG Example - Bash Source: https://github.com/nextpkg/vcfg/blob/main/example/README.md This snippet shows the bash commands to execute the VCFG plugin system example, illustrating how plugins are loaded and managed. ```bash cd plugin go run main.go ``` -------------------------------- ### Running Basic VCFG Example - Bash Source: https://github.com/nextpkg/vcfg/blob/main/example/README.md This snippet provides the bash commands to navigate into the 'basic' example directory and execute the Go application, demonstrating fundamental VCFG configuration loading. ```bash cd basic go run main.go ``` -------------------------------- ### Running CLI VCFG Example - Bash Source: https://github.com/nextpkg/vcfg/blob/main/example/README.md These bash commands demonstrate how to run the VCFG CLI example, showing both the help output and how to specify a configuration file using command-line flags. ```bash cd cli go run main.go --help go run main.go --config config.yaml ``` -------------------------------- ### Running Logger Integration VCFG Example - Bash Source: https://github.com/nextpkg/vcfg/blob/main/example/README.md This bash command runs the VCFG logger integration example, showcasing structured logging with slog and plugin-based logging architecture. ```bash cd logger go run main.go ``` -------------------------------- ### Installing VCFG Library - Bash Source: https://github.com/nextpkg/vcfg/blob/main/README.md This command installs the VCFG Go module, making it available for use in Go projects. It fetches the latest version of the library from its GitHub repository. ```bash go get github.com/nextpkg/vcfg ``` -------------------------------- ### Building Configuration with Multiple Sources - Go Source: https://github.com/nextpkg/vcfg/blob/main/README.md This example showcases VCFG's builder pattern for advanced configuration loading. It defines a complex `AppConfig` struct and integrates with `urfave/cli/v3` to define CLI flags. The builder combines configuration from a file, environment variables (prefixed `MYAPP_`), and CLI flags, also enabling file watching and plugin support for robust application setup. ```go package main import ( "context" "log" "github.com/nextpkg/vcfg" "github.com/urfave/cli/v3" ) type AppConfig struct { Server struct { Host string `json:"host" default:"localhost"` Port int `json:"port" default:"8080"` } `json:"server"` Database struct { URL string `json:"url" validate:"required"` MaxConns int `json:"max_conns" default:"10"` } `json:"database"` Plugins map[string]interface{} `json:"plugins"` } func main() { app := &cli.Command{ Name: "myapp", Flags: []cli.Flag{ &cli.StringFlag{ Name: "config", Value: "config.yaml", Usage: "Configuration file path", }, &cli.IntFlag{ Name: "server.port", Usage: "Server port", }, }, Action: func(ctx context.Context, cmd *cli.Command) error { // Build configuration manager with multiple sources cm, err := vcfg.NewBuilder[AppConfig](). AddFile(cmd.String("config")). // Configuration file AddEnv("MYAPP_"). // Environment variables AddCliFlags(cmd, "."). // CLI flags WithWatch(). // Enable file watching WithPlugin(). // Enable plugins Build(context.Background()) if err != nil { return err } defer cm.Close() config := cm.Get() log.Printf("Server starting on %s:%d", config.Server.Host, config.Server.Port) // Your application logic here return nil }, } if err := app.Run(context.Background(), os.Args); err != nil { log.Fatal(err) } } ``` -------------------------------- ### VCFG Configuration Builder Pattern - Go Source: https://github.com/nextpkg/vcfg/blob/main/example/README.md This Go snippet illustrates the VCFG builder pattern for more flexible configuration loading. It allows adding multiple sources like files and environment variables, and then building the configuration manager. ```go cm, err := vcfg.NewBuilder[MyConfig](). AddFile("config.yaml"). AddEnv("APP"). Build(context.Background()) ``` -------------------------------- ### Setting Up VCFG Development Environment (Bash) Source: https://github.com/nextpkg/vcfg/blob/main/README.md This Bash snippet provides commands for setting up the VCFG development environment. It covers cloning the repository, installing Go module dependencies, and running tests with and without code coverage. ```Bash # Clone the repository git clone https://github.com/nextpkg/vcfg.git cd vcfg # Install dependencies go mod download # Run tests go test ./... # Run tests with coverage go test -cover ./... ``` -------------------------------- ### Simple VCFG Configuration Loading - Go Source: https://github.com/nextpkg/vcfg/blob/main/example/README.md This Go snippet demonstrates the simplest way to load a configuration using VCFG's `MustLoad` function. It loads a `MyConfig` struct from a specified YAML file, panicking on error. ```go config := vcfg.MustLoad[MyConfig]("config.yaml") ``` -------------------------------- ### Running Default Values VCFG Example - Bash Source: https://github.com/nextpkg/vcfg/blob/main/example/README.md This bash command runs the VCFG default values example, illustrating how struct tags can be used to set default values for various data types. ```bash cd defaults go run main.go ``` -------------------------------- ### Loading Configuration Simply - Go Source: https://github.com/nextpkg/vcfg/blob/main/README.md This example demonstrates the simplest way to load configuration using VCFG's `MustLoad` function. It defines a `Config` struct with default values and then loads an instance from `config.json`, printing the loaded configuration. `defer cm.Close()` ensures resources are properly released. ```go package main import ( "fmt" "github.com/nextpkg/vcfg" ) type Config struct { Name string `json:"name" default:"MyApp"` Port int `json:"port" default:"8080"` Debug bool `json:"debug" default:"false"` } func main() { // Load configuration from file cm := vcfg.MustLoad[Config]("config.json") defer cm.Close() config := cm.Get() fmt.Printf("App: %s, Port: %d, Debug: %t\n", config.Name, config.Port, config.Debug) } ``` -------------------------------- ### Running Hot Reload VCFG Example - Bash Source: https://github.com/nextpkg/vcfg/blob/main/example/README.md This bash command executes the VCFG hot reload example, which demonstrates real-time configuration updates upon file changes. It's intended to be run in one terminal while `config.yaml` is modified in another. ```bash cd watch go run main.go ``` -------------------------------- ### Enabling Debug Logging with Slog - Go Source: https://github.com/nextpkg/vcfg/blob/main/example/README.md This Go snippet demonstrates how to configure the default `slog` logger to output debug-level messages to standard output. This is useful for detailed debugging of VCFG applications. ```go slog.SetDefault(slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ Level: slog.LevelDebug, }))) ``` -------------------------------- ### Registering VCFG Plugin - Go Source: https://github.com/nextpkg/vcfg/blob/main/example/README.md This Go snippet shows how to register a custom plugin with the VCFG system. It associates a plugin instance with a unique name, enabling the VCFG framework to manage its lifecycle. ```go vcfg.RegisterPlugin("my-plugin", &MyPlugin{}) ``` -------------------------------- ### Running Logger Demo with Source Info (Bash) Source: https://github.com/nextpkg/vcfg/blob/main/example/logger/README.md This snippet demonstrates how to run the `vcfg` logger plugin demo application using `go run`. It navigates to the example directory and executes the `main.go` file, which is configured via `config.yaml` to include source file information in the logs. ```bash cd /home/ruifenglin/app/vcfg/example/logger go run main.go ``` -------------------------------- ### Example Logger Output with Source Info (JSON) Source: https://github.com/nextpkg/vcfg/blob/main/example/logger/README.md This JSON snippet illustrates an example log entry generated by the `vcfg` logger when `add_source` is enabled and the output format is JSON. It includes fields for time, log level, source file information (function, file, line), message, and additional structured key-value pairs. ```json {"time":"2024-01-15T10:30:45.123Z","level":"INFO","source":{"function":"main.main","file":"/path/to/main.go","line":25},"msg":"Application starting","name":"Logger Demo App","version":"1.0.0"} ``` -------------------------------- ### Inspecting VCFG Configuration Sources - Go Source: https://github.com/nextpkg/vcfg/blob/main/example/README.md This Go snippet shows how to retrieve and iterate over the active configuration sources used by a VCFG configuration manager. This is helpful for understanding the origin and priority of loaded configuration values during debugging. ```go sources := cm.GetSources() for _, source := range sources { fmt.Printf("Source: %s\n", source) } ``` -------------------------------- ### Example Logger Output Without Source Info (Text) Source: https://github.com/nextpkg/vcfg/blob/main/example/logger/README.md This snippet shows an example of `vcfg` logger output in text format when source file information is disabled. It provides a human-readable log entry with timestamp, log level, message, and structured key-value pairs, suitable for development or quick inspection. ```text 10:30:45 INF Application starting name="Logger Demo App" version=1.0.0 ``` -------------------------------- ### Loading Configuration from Files - Go Source: https://github.com/nextpkg/vcfg/blob/main/README.md These examples demonstrate loading configuration from single or multiple files using `vcfg.MustLoad`. When multiple files are provided, VCFG merges them in the specified order, allowing for layered configuration. Supported formats include JSON, YAML, and TOML. ```go // Single file cm := vcfg.MustLoad[Config]("config.yaml") // Multiple files (merged in order) cm := vcfg.MustLoad[Config]("base.yaml", "env.yaml", "local.yaml") ``` -------------------------------- ### Implementing Configuration Validation - Go Source: https://github.com/nextpkg/vcfg/blob/main/example/README.md This Go snippet provides a template for implementing custom validation logic within a VCFG configuration struct. By defining a `Validate` method, developers can enforce data integrity and business rules. ```go func (c *Config) Validate() error { // Add validation logic return nil } ``` -------------------------------- ### Defining Configuration Validation Rules (Go) Source: https://github.com/nextpkg/vcfg/blob/main/README.md This Go snippet demonstrates how to define validation rules for a configuration struct using `github.com/go-playground/validator/v10` tags. It shows examples for required fields, email format, port range, URL format, and minimum string length. ```Go type Config struct { Email string `json:"email" validate:"required,email"` Port int `json:"port" validate:"min=1,max=65535"` URL string `json:"url" validate:"required,url"` Password string `json:"password" validate:"min=8"` } ``` -------------------------------- ### Using VCFG Logger for Structured and Error Logging (Go) Source: https://github.com/nextpkg/vcfg/blob/main/example/logger/README.md This Go code demonstrates how to integrate and use the `vcfg` logger plugin within an application. It shows how to load configuration to initialize the logger, retrieve the global logger instance, and perform structured logging with `logger.Info` and error logging with `logger.Error`, including contextual key-value pairs. It requires the `vcfg` and `vcfg/plugins/builtins` packages. ```go package main import ( "github.com/nextpkg/vcfg" _ "github.com/nextpkg/vcfg/plugins/builtins" "github.com/nextpkg/vcfg/plugins/builtins" ) func main() { // Load configuration (this will start the logger plugin) cm := vcfg.MustLoad[YourConfig]("config.yaml") defer cm.Stop() // Get the global logger instance logger := builtins.GetLogger() // Use structured logging logger.Info("User logged in", "user_id", 12345, "ip", "192.168.1.100", "success", true, ) // Log errors with context logger.Error("Database error", "error", err.Error(), "query", "SELECT * FROM users", ) } ``` -------------------------------- ### Implementing a Custom VCFG Plugin (Go) Source: https://github.com/nextpkg/vcfg/blob/main/README.md This Go code defines a custom VCFG plugin, `MyPlugin`, demonstrating the `Startup`, `Reload`, and `Shutdown` lifecycle methods. It includes a configuration struct with `koanf` tags for default values and shows how to register the plugin with the VCFG system for auto-discovery. ```Go package myplugin import ( "context" "github.com/nextpkg/vcfg/plugins" ) // Plugin configuration type MyPluginConfig struct { plugins.BaseConfig `koanf:",squash"` Setting1 string `koanf:"setting1" default:"default_value"` Setting2 int `koanf:"setting2" default:"42"` } // Plugin implementation type MyPlugin struct { config *MyPluginConfig } func (p *MyPlugin) Startup(ctx context.Context, config any) error { p.config = config.(*MyPluginConfig) // Initialize plugin return nil } func (p *MyPlugin) Reload(ctx context.Context, config any) error { p.config = config.(*MyPluginConfig) // Handle configuration reload return nil } func (p *MyPlugin) Shutdown(ctx context.Context) error { // Cleanup resources return nil } // Register plugin func init() { plugins.RegisterPlugin[MyPlugin, MyPluginConfig]("myplugin", plugins.RegisterOptions{ AutoDiscover: true, }) } ``` -------------------------------- ### Handling Configuration Loading Errors (Go) Source: https://github.com/nextpkg/vcfg/blob/main/README.md This Go snippet illustrates two approaches to error handling when loading configurations with VCFG. It shows how to use the `Builder` pattern for explicit error checking and `MustLoad` for simpler cases where a panic on error is acceptable. ```Go // Using Builder for error handling cm, err := vcfg.NewBuilder[Config](). AddFile("config.yaml"). Build() if err != nil { log.Fatal("Failed to build config:", err) } // Using MustLoad for simple cases (panics on error) cm := vcfg.MustLoad[Config]("config.yaml") ``` -------------------------------- ### Adding Environment Variable Source - Go Source: https://github.com/nextpkg/vcfg/blob/main/README.md This snippet shows how to integrate environment variables as a configuration source using the VCFG builder. `AddEnv("MYAPP_")` instructs VCFG to look for environment variables prefixed with `MYAPP_` and map them to corresponding configuration fields, such as `MYAPP_SERVER_PORT` mapping to `server.port`. ```go builder := vcfg.NewBuilder[Config]() builder.AddEnv("MYAPP_") // Maps MYAPP_SERVER_PORT to server.port ``` -------------------------------- ### Adding Custom Raw Bytes Provider to VCFG (Go) Source: https://github.com/nextpkg/vcfg/blob/main/README.md This Go snippet illustrates how to add a custom configuration provider to VCFG using `rawbytes.Provider`. It allows loading configuration directly from a byte slice, useful for embedding configuration or generating it programmatically. ```Go import "github.com/knadh/koanf/providers/rawbytes" provider := rawbytes.Provider([]byte(`{"key": "value"}`)) builder.AddProvider(provider) ``` -------------------------------- ### Adding CLI Flags to VCFG Builder (Go) Source: https://github.com/nextpkg/vcfg/blob/main/README.md This snippet demonstrates how to integrate command-line interface (CLI) flags into the VCFG configuration builder. It uses dot notation to allow for nested configuration keys, enabling hierarchical configuration through CLI arguments. ```Go builder.AddCliFlags(cmd, ".") // Uses dot notation for nested keys ``` -------------------------------- ### Setting Default Configuration Values (Go) Source: https://github.com/nextpkg/vcfg/blob/main/README.md This Go snippet illustrates how to assign default values to configuration fields using `default` struct tags. This ensures that if a value is not provided by any configuration source, a predefined fallback value is used. ```Go type Config struct { Host string `json:"host" default:"localhost"` Port int `json:"port" default:"8080"` Debug bool `json:"debug" default:"false"` Timeout string `json:"timeout" default:"30s"` } ``` -------------------------------- ### Enabling File Watching for Hot Reloading (Go) Source: https://github.com/nextpkg/vcfg/blob/main/README.md This Go snippet shows how to enable automatic configuration reloading in VCFG by using the `WithWatch()` method on the builder. This feature allows the application to react to changes in configuration files without requiring a restart. ```Go cm, err := vcfg.NewBuilder[Config](). AddFile("config.yaml"). WithWatch(). // Enable file watching Build(context.Background()) ``` -------------------------------- ### Accessing Configuration Concurrently (Go) Source: https://github.com/nextpkg/vcfg/blob/main/README.md This Go snippet demonstrates VCFG's thread-safe nature, allowing concurrent access to configuration objects from multiple goroutines. It shows how to safely retrieve and use the configuration in a loop. ```Go // Safe to call from multiple goroutines config := cm.Get() // Safe concurrent access go func() { for { config := cm.Get() // Use config time.Sleep(time.Second) } }() ``` -------------------------------- ### Configuring Built-in Logger Plugin (YAML) Source: https://github.com/nextpkg/vcfg/blob/main/README.md This YAML configuration snippet shows how to enable and configure the built-in logger plugin for VCFG. It specifies logging level, format, output destination (stdout, stderr, file, or both), file path, source addition, and log rotation settings. ```YAML # config.yaml plugins: logger: type: "logger" level: "info" format: "json" output: "both" # stdout, stderr, file, both file_path: "./logs/app.log" add_source: true enable_rotation: true rotate_interval: "daily" max_file_size: 524288000 # 500MB max_age: 7 ``` -------------------------------- ### Disabling Source File Information in Logger Configuration (YAML) Source: https://github.com/nextpkg/vcfg/blob/main/example/logger/README.md This YAML snippet shows how to modify the `config.yaml` file to disable the inclusion of source file names and line numbers in the `vcfg` logger output. Setting `add_source` to `false` is typically done for production environments to improve performance. ```yaml # Set add_source to false to disable source file information add_source: false ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.