Implements conf.Load to populate tagged structs from a chain of Sources (env, .env, YAML/JSON/TOML, custom). Supports default values, slice separators, nested structs, pointer fields, and a Validator hook. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
46 lines
1.2 KiB
Go
46 lines
1.2 KiB
Go
package conf_test
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"git.juancwu.dev/juancwu/conf"
|
|
"git.juancwu.dev/juancwu/errx"
|
|
)
|
|
|
|
type Config struct {
|
|
BindAddr string `env:"BIND_ADDR" default:":8080"`
|
|
DatabaseURL string `env:"DATABASE_URL"`
|
|
SessionCookieSecure bool `env:"SESSION_COOKIE_SECURE" default:"true"`
|
|
SessionIdleTTL time.Duration `env:"SESSION_IDLE_TTL" default:"24h"`
|
|
JWTSecret []byte `env:"JWT_SECRET"`
|
|
WorkerConcurrency int `env:"WORKER_CONCURRENCY" default:"4"`
|
|
}
|
|
|
|
func (c *Config) Validate() error {
|
|
const op = "config.Validate"
|
|
if strings.TrimSpace(c.DatabaseURL) == "" {
|
|
return errx.New(op, "DATABASE_URL is required")
|
|
}
|
|
if len(c.JWTSecret) == 0 {
|
|
return errx.New(op, "JWT_SECRET is required")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func ExampleLoad() {
|
|
src := conf.MapSource(map[string]string{
|
|
"DATABASE_URL": "postgres://localhost/x",
|
|
"JWT_SECRET": "shh",
|
|
})
|
|
|
|
var cfg Config
|
|
if err := conf.Load(&cfg, src); err != nil {
|
|
fmt.Println("err:", err)
|
|
return
|
|
}
|
|
fmt.Printf("bind=%s workers=%d idle=%s secure=%v",
|
|
cfg.BindAddr, cfg.WorkerConcurrency, cfg.SessionIdleTTL, cfg.SessionCookieSecure)
|
|
// Output: bind=:8080 workers=4 idle=24h0m0s secure=true
|
|
}
|