2025-01-03 22:13:15 +00:00
|
|
|
package config
|
|
|
|
|
|
|
|
import (
|
2025-01-04 02:09:40 +00:00
|
|
|
"context"
|
2025-01-03 22:13:15 +00:00
|
|
|
"flag"
|
|
|
|
"fmt"
|
|
|
|
"os"
|
2025-01-04 02:09:40 +00:00
|
|
|
"runtime/debug"
|
2025-01-03 22:13:15 +00:00
|
|
|
|
|
|
|
"github.com/caarlos0/env/v9"
|
|
|
|
"gopkg.in/yaml.v3"
|
|
|
|
)
|
|
|
|
|
2025-01-04 02:09:40 +00:00
|
|
|
// To be set by ldflags in go build command or
|
|
|
|
// retrieved from build meta below
|
|
|
|
var Version = "(devel)"
|
2025-01-03 22:13:15 +00:00
|
|
|
|
|
|
|
// Calling this will try to load from config if -config is
|
2025-01-04 02:09:40 +00:00
|
|
|
// provided as a file, and will apply any environment overrides
|
|
|
|
// on-top of configuration defaults.
|
|
|
|
// Config is stored in returned context, and can be retrieved
|
|
|
|
// using config.FromCtx(ctx)
|
|
|
|
func LoadConfig(ctx context.Context) (context.Context, error) {
|
2025-01-03 22:13:15 +00:00
|
|
|
configPath := flag.String("config", "", "Path to the configuration file")
|
|
|
|
flag.Parse()
|
|
|
|
|
2025-01-04 02:09:40 +00:00
|
|
|
// Start with defaults
|
|
|
|
// Load from config if provided
|
|
|
|
// Layer on environment
|
|
|
|
cfg, err := loadConfig(*configPath)
|
|
|
|
if err != nil {
|
|
|
|
return ctx, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add config to context, and return
|
|
|
|
// an updated context
|
|
|
|
ctx = cfg.AddToCtx(ctx)
|
|
|
|
return ctx, nil
|
2025-01-03 22:13:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func loadConfig(configPath string) (*AppConfig, error) {
|
2025-01-04 02:09:40 +00:00
|
|
|
cfg := newAppConfig()
|
2025-01-03 22:13:15 +00:00
|
|
|
|
|
|
|
if configPath != "" {
|
|
|
|
file, err := os.Open(configPath)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("could not open config file: %w", err)
|
|
|
|
}
|
|
|
|
defer file.Close()
|
|
|
|
|
|
|
|
decoder := yaml.NewDecoder(file)
|
2025-01-04 02:09:40 +00:00
|
|
|
if err := decoder.Decode(cfg); err != nil {
|
2025-01-03 22:13:15 +00:00
|
|
|
return nil, fmt.Errorf("could not decode config file: %w", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2025-01-04 02:09:40 +00:00
|
|
|
if err := env.Parse(cfg); err != nil {
|
2025-01-03 22:13:15 +00:00
|
|
|
return nil, fmt.Errorf("could not parse environment variables: %w", err)
|
|
|
|
}
|
|
|
|
|
2025-01-04 02:09:40 +00:00
|
|
|
return cfg, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func getVersion() string {
|
|
|
|
if info, ok := debug.ReadBuildInfo(); ok && info.Main.Version != "(devel)" {
|
|
|
|
return info.Main.Version
|
|
|
|
}
|
|
|
|
return Version
|
2025-01-03 22:13:15 +00:00
|
|
|
}
|