### Setup Development Environment and Run Tests (Bash) Source: https://github.com/darkit/sysconf/blob/master/README.md This bash script outlines the steps to set up a development environment for the sysconf project. It includes cloning the repository, downloading dependencies, running unit tests, executing performance benchmarks, and running example applications. This is crucial for contributing to the project. ```bash # 克隆代码 git clone https://github.com/darkit/sysconf.git cd sysconf # 安装依赖 go mod download # 运行测试 go test ./... # 运行性能基准测试 go test -bench=. ./... # 运行示例 cd examples go run . ``` -------------------------------- ### YAML Configuration Example Source: https://github.com/darkit/sysconf/blob/master/README.md A comprehensive example of a YAML configuration file for an application. It includes sections for application settings, server configuration, and database credentials. This format is recommended by the library and demonstrates hierarchical structuring and comments. ```yaml # 应用基础配置 app: name: "MyApp" version: "1.0.0" env: "production" # 服务器配置 server: host: "0.0.0.0" port: 8080 timeout: "30s" features: - http - grpc - websocket # 数据库配置 database: host: "localhost" port: 5432 username: "postgres" password: "secret123" # 可通过环境变量覆盖:export APP_DATABASE_PASSWORD=newpassword timeout: "30s" max_conns: 10 options: ssl_mode: "require" timezone: "UTC" ``` -------------------------------- ### JSON Configuration Example Source: https://github.com/darkit/sysconf/blob/master/README.md An example of a configuration file in JSON format. It demonstrates basic key-value pairs and nested objects for application and database settings. While functional, YAML is generally recommended for its readability and comment support. ```json { "app": { "name": "MyApp", "version": "1.0.0", "env": "production" }, "database": { "host": "localhost", "port": 5432, "timeout": "30s" } } ``` -------------------------------- ### TOML Configuration Example Source: https://github.com/darkit/sysconf/blob/master/README.md An example configuration file using the TOML format. It showcases how to define sections and key-value pairs, including arrays, similar to YAML and JSON. TOML is another supported format for defining application settings. ```toml [app] name = "MyApp" version = "1.0.0" env = "production" [database] host = "localhost" port = 5432 timeout = "30s" [server] features = ["http", "grpc", "websocket"] ``` -------------------------------- ### Dotenv Configuration Example Source: https://github.com/darkit/sysconf/blob/master/README.md A simple example of a .env file format for configuration. It uses key-value pairs separated by an equals sign, typically used for environment variables. This format is lightweight and commonly used for application secrets and simple settings. ```dotenv APP_NAME=MyApp APP_VERSION=1.0.0 DATABASE_HOST=localhost DATABASE_PORT=5432 ``` -------------------------------- ### Install Sysconf Go Package Source: https://github.com/darkit/sysconf/blob/master/README.md This snippet shows how to install the Sysconf Go configuration management library using the go get command. It specifies the system requirement for Go version 1.23 or higher. ```bash go get github.com/darkit/sysconf ``` -------------------------------- ### Unit Test Configuration Handling Source: https://github.com/darkit/sysconf/blob/master/README.md Provides a Go unit test example for the Sysconf configuration library. It demonstrates creating a configuration in memory, asserting configuration reads, testing for concurrency safety with multiple goroutines, and verifying the results of concurrent operations. ```go func TestConfig(t *testing.T) { // 创建测试配置(纯内存模式) cfg, err := sysconf.New( sysconf.WithContent(` app: name: "TestApp" debug: true database: host: "localhost" port: 5432 `), ) require.NoError(t, err) // 测试配置读取 assert.Equal(t, "TestApp", cfg.GetString("app.name")) assert.True(t, cfg.GetBool("app.debug")) assert.Equal(t, 5432, cfg.GetInt("database.port")) // 测试并发安全 var wg sync.WaitGroup for i := 0; i < 100; i++ { wg.Add(1) go func(id int) { defer wg.Done() cfg.Set(fmt.Sprintf("test.key%d", id), fmt.Sprintf("value%d", id)) _ = cfg.GetString("app.name") }(i) } wg.Wait() // 验证并发操作结果 keys := cfg.Keys() assert.GreaterOrEqual(t, len(keys), 100) } ``` -------------------------------- ### Optimize Performance with Environment Variable Prefixes (Go) Source: https://github.com/darkit/sysconf/blob/master/README.md This example shows how to improve performance when dealing with a large number of environment variables by using a prefix with `sysconf.WithEnv`. This allows sysconf to filter relevant variables more efficiently. The library automatically enables optimization strategies for large numbers of variables or high processing times. Requires the sysconf library. ```go // 使用环境变量前缀优化性能 cfg, err := sysconf.New( sysconf.WithEnv("MYAPP"), // 前缀过滤,提升性能 ) // 性能优化特性: // - 环境变量数 > 300 时自动启用优化策略 // - 处理时间 > 100ms 时提供性能建议 // - 智能批处理和时间保护机制 ``` -------------------------------- ### Add Custom Test Scenario (Go) Source: https://github.com/darkit/sysconf/blob/master/examples/benchmark/README.md An example of how to add a custom test scenario within the BenchmarkSuite in Go. It shows how to use `testing.Benchmark` and record the results. ```go // Add custom test scenario func (s *BenchmarkSuite) benchmarkCustomScenario() { result := testing.Benchmark(func(b *testing.B) { // Your test logic for i := 0; i < b.N; i++ { // Execute the operation to be tested } }) s.results = append(s.results, BenchmarkResult{ Name: "CustomTest", // ... other fields }) } ``` -------------------------------- ### Dynamic Validator Management (Go) Source: https://github.com/darkit/sysconf/blob/master/validation/README.md Provides examples for managing validators at runtime, including retrieving the current list, dynamically adding new validators, clearing all validators, and re-adding necessary ones. ```go // 获取当前验证器列表 validators := cfg.GetValidators() fmt.Printf("当前验证器数量: %d\n", len(validators)) // 动态添加验证器 tempValidator := validation.NewRuleValidator("临时验证器") tempValidator.AddStringRule("temp.value", "required") cfg.AddValidator(tempValidator) // 清除所有验证器 cfg.ClearValidators() // 重新添加必要的验证器 cfg.AddValidator(validation.NewDatabaseValidator()) cfg.AddValidator(validation.NewWebServerValidator()) ``` -------------------------------- ### Validation Error Handling Example (Go) Source: https://github.com/darkit/sysconf/blob/master/validation/README.md Illustrates how to handle validation errors when setting configuration values and during configuration unmarshalling. It shows how to print detailed error messages, including specific validation failures for fields like 'server.port'. ```go // 尝试设置无效配置 if err := cfg.Set("server.port", 70000); err != nil { // 验证错误包含详细信息 fmt.Printf("验证失败: %v\n", err) // 输出: validator 'Web Server Configuration Validator' - field 'server.port': port number must be between 1-65535 } // 结构体验证错误 var config AppConfig if err := cfg.Unmarshal(&config); err != nil { fmt.Printf("配置解析失败: %v\n", err) } ``` -------------------------------- ### Concurrent Access Patterns for Sysconf Configuration (Go) Source: https://context7.com/darkit/sysconf/llms.txt This Go code illustrates thread-safe patterns for accessing Sysconf configurations in high-concurrency environments. It includes examples for concurrent reads using atomic operations (zero-lock), concurrent writes protected by mutexes, and a mixed workload simulating typical production traffic. Performance benchmarks suggest high throughput for reads and writes. The underlying architecture utilizes 'atomic.Value' and 'sync.RWMutex'. ```go import ( "sync" "sync/atomic" ) // Concurrent reads (zero-lock, atomic) func readBenchmark(cfg *sysconf.Config) { var wg sync.WaitGroup for i := 0; i < 1000; i++ { wg.Add(1) go func() { defer wg.Done() // Microsecond-level reads _ = cfg.GetString("database.host") _ = cfg.GetInt("database.port") _ = cfg.GetBool("app.debug") }() } wg.Wait() log.Println("1000 concurrent reads completed") } // Concurrent writes (mutex-protected, atomic storage) func writeBenchmark(cfg *sysconf.Config) { var wg sync.WaitGroup for i := 0; i < 100; i++ { wg.Add(1) go func(id int) { defer wg.Done() // Millisecond-level writes cfg.Set(fmt.Sprintf("dynamic.key%d", id), fmt.Sprintf("value%d", id)) }(i) } wg.Wait() log.Println("100 concurrent writes completed") } // Mixed operations (production pattern) func mixedBenchmark(cfg *sysconf.Config) { var wg sync.WaitGroup // 90% reads, 10% writes (typical workload) for i := 0; i < 1000; i++ { wg.Add(1) go func(id int) { defer wg.Done() if id%10 == 0 { cfg.Set("counter", id) } else { _ = cfg.GetString("database.host") } }(i) } wg.Wait() log.Println("Mixed workload completed") } // Race detector tested: go test -race ./... // Performance: 5M+ reads/sec, 10K+ writes/sec // Architecture: atomic.Value + sync.RWMutex ``` -------------------------------- ### ChaCha20-Poly1305 Encryption Setup in Go Source: https://github.com/darkit/sysconf/blob/master/README.md Shows how to enable and use ChaCha20-Poly1305 authenticated encryption for securing sensitive configuration data. It demonstrates initializing the configuration with a secret password for encryption and then automatically encrypting/decrypting sensitive fields like database passwords and API keys. ```go // 轻量级加密(推荐入门) cfg, err := sysconf.New( sysconf.WithPath("configs"), sysconf.WithName("app"), sysconf.WithEncryption("your-secret-password"), // 🔐 启用加密 sysconf.WithContent(defaultConfig), ) // 敏感配置自动加密存储 cfg.Set("database.password", "super-secret-password") cfg.Set("api.secret_key", "sk-1234567890abcdef") // 读取时自动解密 dbPassword := cfg.GetString("database.password") apiKey := cfg.GetString("api.secret_key") ``` -------------------------------- ### Conditional Validation Based on Configuration Values (Go) Source: https://github.com/darkit/sysconf/blob/master/validation/README.md Illustrates how to perform conditional validation using `AddValidateFunc`. This example checks if caching is enabled and, if so, ensures that a Redis host is configured. ```go // 基于配置值的条件验证 cfg.AddValidateFunc(func(config map[string]any) error { // 如果启用了缓存,必须配置Redis if cacheEnabled := getNestedValue(config, "app.cache.enabled"); cacheEnabled == true { if redisHost := getNestedValue(config, "redis.host"); redisHost == nil || redisHost == "" { return fmt.Errorf("启用缓存时必须配置Redis主机地址") } } return nil }) ``` -------------------------------- ### Error Aggregation Example (Go) Source: https://github.com/darkit/sysconf/blob/master/validation/README.md Demonstrates how the validator aggregates multiple validation errors. It shows setting several invalid configuration values sequentially and then retrieving all aggregated errors using `cfg.GetValidationErrors()`, printing each one. ```go // 同时设置多个无效值 cfg.Set("server.port", 70000) // 端口错误 cfg.Set("database.host", "") // 主机名错误 cfg.Set("redis.db", 20) // Redis DB索引错误 // 获取所有验证错误 errors := cfg.GetValidationErrors() // 自定义方法,返回所有错误 for _, err := range errors { fmt.Printf("验证错误: %v\n", err) } ``` -------------------------------- ### Adding Custom Functional Validators (Go) Source: https://github.com/darkit/sysconf/blob/master/validation/README.md Demonstrates how to add custom validation logic using `AddValidateFunc`. Examples include checking database connection consistency and ensuring SSL is enabled in production environments. ```go // 自定义业务逻辑验证 cfg.AddValidateFunc(func(config map[string]any) error { // 检查数据库连接配置的一致性 if dbConfig, exists := config["database"].(map[string]any); exists { if dbType, ok := dbConfig["type"].(string); ok && dbType == "mysql" { if port, ok := dbConfig["port"].(int); ok && port != 3306 { return fmt.Errorf("MySQL数据库应使用默认端口3306") } } } return nil }) // 环境特定验证 cfg.AddValidateFunc(func(config map[string]any) error { if appConfig, exists := config["app"].(map[string]any); exists { if env, ok := appConfig["env"].(string); ok && env == "production" { // 生产环境必须启用SSL if serverConfig, exists := config["server"].(map[string]any); exists { if sslConfig, exists := serverConfig["ssl"].(map[string]any); exists { if enabled, ok := sslConfig["enabled"].(bool); !ok || !enabled { return fmt.Errorf("生产环境必须启用SSL") } } } } } return nil }) ``` -------------------------------- ### Struct Mapping with Sysconf in Go Source: https://github.com/darkit/sysconf/blob/master/README.md Shows how to use Sysconf's struct mapping feature to unmarshal configuration directly into Go structs. This includes defining structs with `config` tags for mapping and `validate` tags for validation rules. The example demonstrates accessing configuration values through the strongly-typed struct. ```go // 定义配置结构体 type AppConfig struct { App struct { Name string `config:"name" default:"MyApp" validate:"required,min=1" Version string `config:"version" default:"1.0.0" validate:"required,semver" Env string `config:"env" default:"development" validate:"required,oneof=development test prod" } `config:"app"` Database struct { Host string `config:"host" default:"localhost" validate:"required,hostname_rfc1123" Port int `config:"port" default:"5432" validate:"required,min=1,max=65535" Username string `config:"username" default:"postgres" validate:"required,min=1" Password string `config:"password" validate:"required,min=1" Timeout time.Duration `config:"timeout" default:"30s" validate:"required" MaxConns int `config:"max_conns" default:"10" validate:"min=1,max=100" } `config:"database"` } func main() { cfg, _ := sysconf.New(/* 配置选项 */) var config AppConfig if err := cfg.Unmarshal(&config); err != nil { log.Fatal("配置解析失败:", err) } // 类型安全的配置访问 fmt.Printf("应用: %s v%s\n", config.App.Name, config.App.Version) fmt.Printf("数据库: %s:%d\n", config.Database.Host, config.Database.Port) } ``` -------------------------------- ### Retrieve Configuration Values with Type Safety in Go Source: https://context7.com/darkit/sysconf/llms.txt Shows various methods for retrieving configuration values using type-safe getters provided by Sysconf. It covers basic types, slices, maps, handling errors for missing keys, checking key existence, and provides examples for different data types including strings, integers, booleans, durations, times, floats, slices, and maps. ```go // Basic type getters with defaults host := cfg.GetString("database.host", "localhost") port := cfg.GetInt("database.port", "5432") debug := cfg.GetBool("app.debug", "false") timeout := cfg.GetDuration("database.timeout") // Returns time.Duration timestamp := cfg.GetTime("app.created_at") // Returns time.Time weight := cfg.GetFloat("metrics.weight", "0.95") // Multi-parameter syntax (alternative) host := cfg.GetString("database", "host", "localhost") // Slice getters features := cfg.GetStringSlice("server.features") // []string ports := cfg.GetIntSlice("server.ports") // []int weights := cfg.GetFloatSlice("analytics.weights") // []float64 flags := cfg.GetBoolSlice("feature.flags") // []bool // Map getters options := cfg.GetStringMap("database.options") // map[string]interface{} headers := cfg.GetStringMapString("http.headers") // map[string]string // Error handling value, err := cfg.GetWithError("api.key") if err != nil { log.Printf("Config key not found: %v", err) } // Check existence if cfg.IsSet("optional.feature") { feature := cfg.GetString("optional.feature") log.Printf("Feature enabled: %s", feature) } // Example with all types log.Printf("Server: %s:%d", host, port) log.Printf("Timeout: %v, Debug: %t", timeout, debug) log.Printf("Features: %v", features) log.Printf("Options: %v", options) ``` -------------------------------- ### Run Benchmark Tool (Bash) Source: https://github.com/darkit/sysconf/blob/master/examples/benchmark/README.md This snippet demonstrates how to navigate to the benchmark directory and execute the benchmark tool using Go. ```bash # Enter the benchmark directory cd examples/benchmark # Run the benchmark tool go run benchmark_tool.go ``` -------------------------------- ### Basic Sysconf Usage in Go Source: https://github.com/darkit/sysconf/blob/master/README.md Demonstrates the basic usage of Sysconf for creating a configuration instance. It shows how to set default configurations, specify config file paths and names, and read configuration values of different types (string, int, bool, duration) in a thread-safe manner. Includes a high-concurrency scenario test. ```go package main import ( "log" "time" "fmt" "github.com/darkit/sysconf" "github.com/darkit/sysconf/validation" ) func main() { // 创建高性能、线程安全的配置实例 cfg, err := sysconf.New( sysconf.WithContent(defaultConfig), // 默认配置内容 sysconf.WithPath("configs"), // 配置文件目录 sysconf.WithName("app"), // 配置文件名 sysconf.WithMode("yaml"), // 配置格式 ) if err != nil { log.Fatal("创建配置失败:", err) } // 类型安全的配置读取(完全线程安全) host := cfg.GetString("database.host", "localhost") port := cfg.GetInt("database.port", "5432") debug := cfg.GetBool("app.debug", "false") timeout := cfg.GetDuration("database.timeout") log.Printf("数据库连接: %s:%d", host, port) // 高并发场景演示 - 无竞态条件 go func() { for i := 0; i < 1000; i++ { cfg.Set(fmt.Sprintf("dynamic.key%d", i), fmt.Sprintf("value%d", i)) } }() go func() { for i := 0; i < 1000; i++ { _ = cfg.GetString("database.host") } }() log.Println("✅ 高并发操作完成,无任何竞态条件") } const defaultConfig = ` app: name: "MyApp" version: "1.0.0" debug: false database: host: "localhost" port: 5432 timeout: "30s" server: features: ["http", "grpc", "websocket"] ports: [8080, 8443] ` ``` -------------------------------- ### Go: Global Singleton Pattern with Sysconf Source: https://context7.com/darkit/sysconf/llms.txt Shows how to implement a global singleton pattern for application configuration using sysconf's registration capabilities. This allows for easily accessing common application settings like name and version from anywhere in the application. ```go // Global singleton pattern sysconf.Register("global", "app_name", "GlobalApp") sysconf.Register("global", "version", "2.0.0") appName := sysconf.Default().GetString("global.app_name") version := sysconf.Default().GetString("global.version") ``` -------------------------------- ### Create Sysconf Configuration Instance with Options in Go Source: https://context7.com/darkit/sysconf/llms.txt Demonstrates how to create a thread-safe configuration instance using Sysconf. It showcases various options for setting paths, naming, content, environment variable integration, encryption, validators, and tuning write/cache behaviors. Error handling for instance creation is also included. ```go package main import ( "log" "time" "github.com/darkit/sysconf" "github.com/darkit/sysconf/validation" ) const defaultConfig = ` app: name: "MyApp" version: "1.0.0" debug: false database: host: "localhost" port: 5432 timeout: "30s" password: "demo" server: host: "0.0.0.0" port: 8080 features: ["http", "grpc"] ` func main() { // Create configuration with validation and encryption cfg, err := sysconf.New( sysconf.WithPath("configs"), // Config directory sysconf.WithName("app"), // File name (app.yaml) sysconf.WithMode("yaml"), // Format: yaml/json/toml sysconf.WithContent(defaultConfig), // Default content sysconf.WithEnv("APP"), // Enable smart env vars sysconf.WithEncryption("secret-password"), // ChaCha20-Poly1305 sysconf.WithValidators( validation.NewDatabaseValidator(), validation.NewWebServerValidator(), ), sysconf.WithWriteFlushDelay(3*time.Second), // Batch writes sysconf.WithCacheTiming(0, 100*time.Millisecond), // Cache tuning ) if err != nil { log.Fatalf("Failed to create config: %v", err) } log.Printf("Config loaded: %s v%s", cfg.GetString("app.name"), cfg.GetString("app.version")) } ``` -------------------------------- ### Go: Performance Tuning with Sysconf Source: https://context7.com/darkit/sysconf/llms.txt Illustrates performance tuning options for sysconf, including configuring write delays for batching changes and setting cache warmup and rebuild delays. These settings help optimize configuration loading and update performance. ```go // Performance tuning cfg, _ = sysconf.New( // Write delay: batch changes (0 = immediate) sysconf.WithWriteFlushDelay(500*time.Millisecond), // Cache timing: warmup and rebuild delays sysconf.WithCacheTiming(0, 100*time.Millisecond), ) ``` -------------------------------- ### Validator Reuse for Performance Optimization (Go) Source: https://github.com/darkit/sysconf/blob/master/validation/README.md Suggests reusing validator instances for performance optimization. The example shows defining a global slice of common validators that can be passed to `sysconf.New` to avoid repeated initialization of the same validators. ```go // ✅ 推荐:验证器复用 var ( commonValidators = []validation.Validator{ validation.NewDatabaseValidator(), validation.NewWebServerValidator(), validation.NewRedisValidator(), } ) func createConfig() *sysconf.Config { cfg, _ := sysconf.New( sysconf.WithValidators(commonValidators...), ) return cfg } ``` -------------------------------- ### Go: Debugging and Introspection with Sysconf Source: https://context7.com/darkit/sysconf/llms.txt Demonstrates how to enable debug logging, retrieve all configuration keys, access all settings, and check for the existence of specific configuration keys using the sysconf library. This is useful for understanding the current configuration state and troubleshooting. ```go // Debug and introspection cfg, _ := sysconf.New( sysconf.WithLogLevel("debug"), // Enable detailed logging ) // Get all config keys keys := cfg.Keys() log.Printf("Config keys: %v", keys) // Export all settings allSettings := cfg.AllSettings() log.Printf("All settings: %+v", allSettings) // Check key existence if cfg.IsSet("optional.feature") { feature := cfg.GetString("optional.feature") log.Printf("Feature: %s", feature) } ``` -------------------------------- ### Load Configuration with Default Content (Go) Source: https://github.com/darkit/sysconf/blob/master/README.md This snippet shows how to initialize a sysconf configuration object by providing default content directly using the `WithContent` option. This is useful when no external configuration file is present or a base configuration is always needed. It utilizes the sysconf library. ```go // 使用WithContent提供默认配置 cfg, err := sysconf.New( sysconf.WithPath("configs"), sysconf.WithName("app"), sysconf.WithContent(defaultConfig), // 提供默认配置 ) ``` -------------------------------- ### Go Sysconf Advanced Configuration Options Source: https://github.com/darkit/sysconf/blob/master/README.md Details advanced options for initializing Sysconf, including setting configuration paths, formats, names, default content, and environment variable integration. It also covers validators, encryption, and integration with command-line flag parsers like Cobra. ```go cfg, err := sysconf.New( // 基础选项 sysconf.WithPath("configs"), // 配置文件目录 sysconf.WithMode("yaml"), // 配置格式 sysconf.WithName("app"), // 配置文件名 // 默认配置 sysconf.WithContent(defaultConfig), // 默认配置内容 // 环境变量配置 sysconf.WithEnv("APP"), // 便利函数:启用智能大小写匹配 // 或完整配置(高级用法) sysconf.WithEnvOptions(sysconf.EnvOptions{ Prefix: "APP", // 环境变量前缀 Enabled: true, // 启用环境变量覆盖 SmartCase: true, // 启用智能大小写匹配 }), // 验证器配置 sysconf.WithValidators( validation.NewDatabaseValidator(), validation.NewWebServerValidator(), ), // 加密配置 sysconf.WithEncryption("secret-password"), // 启用加密 // 命令行集成 sysconf.WithPFlags(cmd.Flags()), // Cobra集成 ) ``` -------------------------------- ### Debug Configuration Settings Source: https://github.com/darkit/sysconf/blob/master/README.md Illustrates debugging techniques for Sysconf configurations. This includes enabling debug logging, exporting all current settings, checking for the existence of a configuration key, and retrieving a list of all configuration keys. ```go // 启用调试日志 cfg, err := sysconf.New( sysconf.WithLogLevel("debug"), // 开启详细日志 // ... 其他选项 ) // 导出当前所有配置 allSettings := cfg.AllSettings() fmt.Printf("当前配置: %+v\n", allSettings) // 检查配置键是否存在 if !cfg.IsSet("some.key") { log.Println("配置键不存在:", "some.key") } // 获取所有配置键 keys := cfg.Keys() log.Printf("配置键列表: %v", keys) ``` -------------------------------- ### Organizing Validators by Module (Go) Source: https://github.com/darkit/sysconf/blob/master/validation/README.md Presents a recommended approach for organizing validators by module and environment. The `setupValidators` function shows how to add common validators, environment-specific validators (e.g., production, development), and business logic validators to a configuration object. ```go // ✅ 推荐:按模块组织验证器 func setupValidators(cfg *sysconf.Config, env string) { // 基础验证器(所有环境) cfg.AddValidator(validation.NewDatabaseValidator()) cfg.AddValidator(validation.NewWebServerValidator()) // 环境特定验证器 switch env { case "production": cfg.AddValidator(validation.NewEmailValidator()) cfg.AddValidator(validation.NewAPIValidator()) case "development": cfg.AddValidator(validation.NewLogValidator()) } // 业务逻辑验证器 cfg.AddValidator(createBusinessValidator()) } ``` -------------------------------- ### Environment Variable Integration with Smart Case Matching - Go Source: https://context7.com/darkit/sysconf/llms.txt Demonstrates how to integrate environment variables into configuration using sysconf. Supports case-insensitive matching, custom prefixes, and provides performance optimizations for large numbers of environment variables. Configuration values can be retrieved as strings, integers, or durations, automatically parsing values from environment variables. ```go import "os" import "log" import "context" import "sync/atomic" // Assuming sysconf and AppConfig are defined elsewhere // type AppConfig struct { ... } // func reconnectDB(host string, port int) error { ... } // var defaultConfig string // Set environment variables (supports multiple formats) os.Setenv("APP_DATABASE_HOST", "prod-server") // UPPERCASE os.Setenv("app_database_port", "5433") // lowercase os.Setenv("App_Database_Password", "secret123") // Mixed case os.Setenv("database_timeout", "45s") // No prefix // Create config with smart env support cfg, err := sysconf.New( sysconf.WithPath("configs"), sysconf.WithContent(defaultConfig), sysconf.WithEnv("APP"), // Prefix + SmartCase enabled ) // All env formats work automatically host := cfg.GetString("database.host") // Returns "prod-server" port := cfg.GetInt("database.port") // Returns 5433 password := cfg.GetString("database.password") // Returns "secret123" timeout := cfg.GetDuration("database.timeout") // Returns 45s log.Printf("Env override - Host: %s", host) log.Printf("Env override - Port: %d", port) // Advanced env options cfg, err = sysconf.New( sysconf.WithEnvOptions(sysconf.EnvOptions{ Prefix: "MYAPP", // Custom prefix Enabled: true, // Enable env vars SmartCase: true, // Multi-case support }), ) // Basic hot reload cfg.Watch(func() { log.Println("Config changed, reloading...") var newConfig AppConfig if err := cfg.Unmarshal(&newConfig); err != nil { log.Printf("Reload failed: %v", err) return } // updateApplication(&newConfig) // Assuming this function exists log.Println("Application reconfigured successfully") }) // Context-based hot reload with cancellation ctx, cancel := context.WithCancel(context.Background()) defer cancel() stopFunc := cfg.WatchWithContext(ctx, func() { log.Println("Config file updated") // Reload logic host := cfg.GetString("database.host") port := cfg.GetInt("database.port") // Reconnect database with new settings if err := reconnectDB(host, port); err != nil { log.Printf("Failed to reconnect: %v", err) return } log.Println("Database reconnected with new config") }) // Stop watching when needed time.AfterFunc(1*time.Hour, func() { cancel() // or stopFunc() log.Println("Config watching stopped") }) // Thread-safe hot reload with atomic config type App struct { config atomic.Value // Stores *AppConfig cfg *sysconf.Config } func (app *App) WatchConfig() { app.cfg.Watch(func() { var newConfig AppConfig if err := app.cfg.Unmarshal(&newConfig); err != nil { log.Printf("Reload failed: %v", err) return } // Atomic swap - zero-downtime update app.config.Store(&newConfig) log.Println("Config atomically updated") }) } func (app *App) GetConfig() *AppConfig { return app.config.Load().(*AppConfig) } ``` -------------------------------- ### 从 base64 密钥恢复加密器 (Go) Source: https://github.com/darkit/sysconf/blob/master/examples/encryption_demo/README.md 展示了如何使用 `sysconf.NewDefaultCryptoFromKey` 函数,从 base64 编码的密钥字符串恢复出默认的加密器实例。然后可以将此加密器通过 `sysconf.WithEncryptionCrypto` 应用到 sysconf 配置中。 ```Go // 从已保存的密钥恢复加密器 crypto, err := sysconf.NewDefaultCryptoFromKey("SfHvn3Es9KwVMwYjxILh5gjavijaQlOVF2Pwc7oyiqM=") config, err := sysconf.New( sysconf.WithEncryptionCrypto(crypto), ) ``` -------------------------------- ### Go Sysconf Tuning Options Source: https://github.com/darkit/sysconf/blob/master/README.md Demonstrates how to create a new Sysconf instance with custom tuning options. It highlights `WithWriteFlushDelay` for controlling write latency and `WithCacheTiming` for cache warm-up and rebuild intervals. These options allow fine-grained control over persistence and caching behavior. ```go cfg, err := sysconf.New( sysconf.WithWriteFlushDelay(500*time.Millisecond), // 调整写入延迟,0 表示立即写入 sysconf.WithCacheTiming(0, 100*time.Millisecond), // 控制缓存预热与重建延迟 ) ``` -------------------------------- ### Separate Configurations by Environment Source: https://github.com/darkit/sysconf/blob/master/README.md Details a recommended approach for managing configurations across different environments (development, testing, production) using Sysconf. It suggests organizing configuration files by environment and dynamically loading the appropriate configuration based on an environment variable. ```go // ✅ 推荐:按环境组织配置文件 // configs/ // ├── base.yaml # 基础配置 // ├── dev.yaml # 开发环境 // ├── test.yaml # 测试环境 // └── prod.yaml # 生产环境 env := os.Getenv("APP_ENV") if env == "" { env = "dev" } cfg, err := sysconf.New( sysconf.WithName(env), sysconf.WithEnv(strings.ToUpper(env)), // ... ) ``` -------------------------------- ### Load Configuration from Environment Variables (Go) Source: https://github.com/darkit/sysconf/blob/master/README.md This code illustrates how to load configuration from environment variables using sysconf. The `WithEnv` option supports flexible casing (lowercase, uppercase, mixed case) for environment variable names, making it more adaptable to different deployment environments. It requires the sysconf library. ```go // 使用智能大小写匹配 cfg, err := sysconf.New( sysconf.WithEnv("APP"), // 支持各种大小写格式 ) // 支持的环境变量格式 // app_database_host=localhost ✅ 小写 // APP_DATABASE_HOST=localhost ✅ 大写 // App_Database_Host=localhost ✅ 混合大小写 ``` -------------------------------- ### Handle Configuration Errors Gracefully Source: https://github.com/darkit/sysconf/blob/master/README.md Provides guidance on robust error handling when parsing configurations with Sysconf. It shows how to use `Unmarshal` and gracefully fall back to default configurations if parsing fails, ensuring application stability. ```go // ✅ 推荐:优雅的错误处理 if err := cfg.Unmarshal(&config); err != nil { log.Printf("配置解析失败: %v", err) // 使用默认配置继续运行 config = getDefaultConfig() } ``` -------------------------------- ### CI/CD Workflow for Benchmarking (YAML) Source: https://github.com/darkit/sysconf/blob/master/examples/benchmark/README.md This YAML configuration defines a GitHub Actions workflow to automatically run benchmarks on push or pull requests. It checks out code, sets up Go, runs the benchmark tool, and uploads the results as artifacts. ```yaml # .github/workflows/benchmark.yml name: Benchmarkon: [push, pull_request] jobs: benchmark: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-go@v2 with: go-version: 1.21 - name: Run Benchmark run: | cd examples/benchmark go run benchmark_tool.go - name: Upload Results uses: actions/upload-artifact@v2 with: name: benchmark-results path: | examples/benchmark/benchmark_report.md examples/benchmark/benchmark_trends.json ``` -------------------------------- ### Design Configuration Structures Source: https://github.com/darkit/sysconf/blob/master/README.md Presents best practices for designing configuration structures in Go using Sysconf. It recommends organizing configurations by module and using structs with `config`, `default`, and `validate` tags for better readability, maintainability, and automatic validation. ```go // ✅ 推荐:按模块组织配置 type Config struct { App AppConfig `config:"app"` Database DatabaseConfig `config:"database"` Server ServerConfig `config:"server"` Cache CacheConfig `config:"cache"` } // ✅ 推荐:合理使用默认值和验证 type DatabaseConfig struct { Host string `config:"host" default:"localhost" validate:"hostname"` Port int `config:"port" default:"5432" validate:"min=1,max=65535"` Password string `config:"password" validate:"required,min=8"` // 敏感信息无默认值 } ``` -------------------------------- ### Update Configuration Items Source: https://github.com/darkit/sysconf/blob/master/README.md Demonstrates how to update individual configuration items and perform batch updates. It highlights the automatic validation and recommended batch update approach for efficiency and consistency. ```go // 更新单个配置项(自动验证) if err := cfg.Set("database.host", "new-host"); err != nil { log.Printf("配置更新失败: %v", err) } // 批量更新(推荐) updates := map[string]interface{}{ "database.host": "new-host", "database.port": 5433, "server.debug": true, } for key, value := range updates { if err := cfg.Set(key, value); err != nil { log.Printf("更新 %s 失败: %v", key, err) } } ``` -------------------------------- ### Predefined Validator Instantiation in Go Source: https://github.com/darkit/sysconf/blob/master/README.md Demonstrates the creation of various enterprise-grade predefined validators. These include validators for databases, web servers, Redis, email configurations, API settings, and logging, each designed to validate specific types of configurations. ```go // 数据库配置验证器 validator := validation.NewDatabaseValidator() // 验证:主机名、端口范围、用户名、密码、数据库类型等 // Web服务器验证器 validator := validation.NewWebServerValidator() // 验证:服务器配置、SSL设置、运行模式等 // Redis验证器 validator := validation.NewRedisValidator() // 验证:Redis连接、数据库索引、地址列表等 // 邮件配置验证器 validator := validation.NewEmailValidator() // 验证:SMTP配置、邮箱格式、认证设置等 // API配置验证器 validator := validation.NewAPIValidator() // 验证:API端点、认证密钥、超时设置等 // 日志配置验证器 validator := validation.NewLogValidator() // 验证:日志级别、输出格式、文件路径等 ``` -------------------------------- ### Batch Configuration Update and Validation (Go) Source: https://github.com/darkit/sysconf/blob/master/validation/README.md Demonstrates how to perform batch updates to configuration settings and validates each update using the configured validators. It iterates through a map of key-value pairs, applying each setting and logging any validation errors encountered. ```go // 批量设置配置并验证 updates := map[string]interface{}{ "server.host": "api.example.com", "server.port": 443, "database.host": "db.example.com", "database.port": 5432, "redis.host": "cache.example.com", } // 所有更新都会经过验证器验证 for key, value := range updates { if err := cfg.Set(key, value); err != nil { log.Printf("设置 %s 失败: %v", key, err) } } ``` -------------------------------- ### Go: Multi-Format Support with Sysconf Source: https://context7.com/darkit/sysconf/llms.txt Highlights sysconf's ability to handle multiple configuration file formats, including YAML, JSON, TOML, and environment variables. This allows flexibility in how configuration is stored and managed. ```go // Multi-format support yamlCfg, _ := sysconf.New(sysconf.WithMode("yaml")) jsonCfg, _ := sysconf.New(sysconf.WithMode("json")) tomlCfg, _ := sysconf.New(sysconf.WithMode("toml")) envCfg, _ := sysconf.New(sysconf.WithMode("env")) ``` -------------------------------- ### Sysconf Validation System with Built-in and Custom Rules Source: https://context7.com/darkit/sysconf/llms.txt Demonstrates how to initialize Sysconf with built-in validators, field-level validation, custom rule validators, composite validators, and function-based validators. It covers adding, managing, and testing various validation rules for configuration settings. ```go // Built-in validators (6 predefined) cfg, err := sysconf.New( sysconf.WithContent(defaultConfig), sysconf.WithValidators( validation.NewDatabaseValidator(), // DB config rules validation.NewWebServerValidator(), // Server config rules validation.NewRedisValidator(), // Redis config rules validation.NewEmailValidator(), // Email config rules validation.NewAPIValidator(), // API config rules validation.NewLogValidator(), // Logging config rules ), ) // Field-level validation (automatic on Set) err := cfg.Set("server.port", 8080) // ✅ Valid err = cfg.Set("server.port", 70000) // ❌ Rejected by validator err = cfg.Set("database.host", "localhost") // ✅ Valid hostname // Custom rule validator businessValidator := validation.NewRuleValidator("Business Validator") // Add validation rules businessValidator.AddRule("company.name", validation.Required("Company name is required")) businessValidator.AddRule("company.tax_id", validation.Pattern(`^\d{18}$`, "Tax ID must be 18 digits")) businessValidator.AddStringRule("company.industry", "enum:technology,finance,healthcare") businessValidator.AddStringRule("company.employee_count", "range:1,10000") cfg.AddValidator(businessValidator) // Test validation cfg.Set("company.name", "Tech Corp") cfg.Set("company.tax_id", "123456789012345678") cfg.Set("company.industry", "technology") cfg.Set("company.employee_count", 250) // 30+ validation rules available: // Network: email, url, ipv4, ipv6, hostname, port // Format: uuid, json, base64, alphanum, regex, phonenumber // Numeric: min, max, range, length // Business: creditcard, timezone, datetime // Enum: enum, oneof // Composite validator composite := validation.NewCompositeValidator( "Enterprise Validator", validation.NewDatabaseValidator(), validation.NewWebServerValidator(), validation.NewRedisValidator(), ) cfg.AddValidator(composite) // Function-based validator cfg.AddValidateFunc(func(config map[string]any) error { if env := config["app"].(map[string]any)["env"]; env == "production" { if ssl := config["server"].(map[string]any)["ssl"]; ssl != true { return fmt.Errorf("SSL required in production") } } return nil }) // Dynamic validator management validators := cfg.GetValidators() log.Printf("Active validators: %d", len(validators)) cfg.ClearValidators() // Remove all cfg.AddValidator(validation.NewDatabaseValidator()) // Re-add ``` -------------------------------- ### Graceful Error Handling Strategy (Go) Source: https://github.com/darkit/sysconf/blob/master/validation/README.md Outlines a recommended strategy for graceful error handling during configuration loading. The `loadConfig` function demonstrates creating a configuration, handling creation errors, and managing unmarshalling errors by falling back to default configurations and logging the issue. ```go // ✅ 推荐:优雅的错误处理 func loadConfig() (*AppConfig, error) { cfg, err := sysconf.New(/* 选项 */) if err != nil { return nil, fmt.Errorf("创建配置失败: %w", err) } var config AppConfig if err := cfg.Unmarshal(&config); err != nil { // 配置验证失败,使用默认配置 log.Printf("配置验证失败,使用默认配置: %v", err) return getDefaultConfig(), nil } return &config, nil } ``` -------------------------------- ### Go Hot Reloading with Context Source: https://github.com/darkit/sysconf/blob/master/README.md Monitors configuration files for changes and reloads them using a provided context. It includes debouncing, concurrency safety, error recovery, and intelligent file watching. The `WatchWithContext` function returns a stop channel to explicitly halt the monitoring. ```go ctx, cancel := context.WithCancel(context.Background()) defer cancel() stop := cfg.WatchWithContext(ctx, func() { log.Println("配置文件已更新") var newConfig AppConfig if err := cfg.Unmarshal(&newConfig); err != nil { log.Printf("配置重载失败: %v", err) return } updateApplication(&newConfig) }) // 在需要时显式停止监听 stop() ``` -------------------------------- ### Go: Memory-Only Configuration with Sysconf Source: https://context7.com/darkit/sysconf/llms.txt Demonstrates creating a configuration instance that resides entirely in memory and does not persist to a file. This is useful for temporary configurations or configurations generated dynamically. ```go // Memory-only config (no file persistence) cfg, _ = sysconf.New( sysconf.WithContent(defaultConfig), // No WithName() = memory only ) ``` -------------------------------- ### sysconf 自动生成加密密钥 (Go) Source: https://github.com/darkit/sysconf/blob/master/examples/encryption_demo/README.md 展示了如何通过传递空字符串给 `sysconf.WithEncryption` 来让 sysconf 自动生成加密密钥。生成的密钥可以通过 `config.GetEncryptionKey()` 获取,便于备份和恢复。 ```Go config, err := sysconf.New( sysconf.WithEncryption(""), // 空字符串自动生成密钥 sysconf.WithPath("./configs"), sysconf.WithName("app"), ) // 获取生成的密钥用于备份 key := config.GetEncryptionKey() ```