configx/example/example.go

52 lines
1.1 KiB
Go

package main
import (
"fmt"
"log"
"gitea.cccvno1.com/chenchi/configx"
)
type AppConfig struct {
Server struct {
Port int `config:"port"`
Host string `config:"host"`
} `config:"server"`
Database struct {
DSN string `config:"dsn"`
} `config:"database"`
Features struct {
EnableCache bool `config:"enable_cache"`
} `config:"features"`
LogLevel string `config:"log_level"`
}
func main() {
var cfg AppConfig
c, err := configx.New(&cfg,
configx.WithEnvFile(".env"),
configx.WithConfigFile("config.yaml"),
configx.WithAutoReload(true),
)
if err != nil {
log.Fatalf("Failed to load config: %v", err)
}
printConfig(c)
// Watch for changes in the log level
c.WatchField("log_level", func(newValue interface{}) {
fmt.Printf("Log level changed to: %v\n", newValue)
printConfig(c)
})
select {}
}
func printConfig(cfg *configx.Config) {
fmt.Printf("Server: %s:%d\n", cfg.GetString("server.host"), cfg.GetInt("server.port"))
fmt.Printf("Database DSN: %s\n", cfg.GetString("database.dsn"))
fmt.Printf("Features: EnableCache=%v\n", cfg.GetBool("features.enable_cache"))
fmt.Printf("Log level: %s\n", cfg.GetString("log_level"))
}