Documentation
¶
Overview ¶
Package xconfig provides a flexible configuration loader for Go applications.
xconfig supports populating struct fields from both YAML files and environment variables, with the ability to overlay environment values, apply default values, and handle custom types via encoding.TextUnmarshaler.
Features ¶
- Load configuration from a YAML file.
- Overlay configuration values from environment variables.
- Support for default field values via struct tags.
- Custom field parsing via encoding.TextUnmarshaler (e.g., time.Time, time.Duration).
Usage ¶
To use xconfig, define a struct representing your configuration. Fields can be tagged with `xconfig:"key,default"` to specify a different name for the key and an optional default value.
type Config struct {
Addr string `xconfig:"bind_addr,localhost:8080"`
Timeout time.Duration `xconfig:",5s"`
}
Then, call Unmarshal:
var cfg Config
err := xconfig.Unmarshal(&cfg, xconfig.Options{YAMLFile: "config.yml"})
Tag Format ¶
Struct tags accept two values separated by a comma:
- `key`: The key used in both YAML and environment overlays (case-insensitive).
- `default`: The default value to assign if no value is present.
Extensibility ¶
xconfig uses reflection to analyze struct fields and can be extended to support custom decoding logic by implementing `encoding.TextUnmarshaler` interface.
Example ¶
type Config struct {
Port int `xconfig:",8000"`
BindIP net.IP `xconfig:"bind_ip,127.0.0.1"`
Timeout time.Duration `xconfig:",5s"`
Debug bool
Hosts []string
}
func main() {
var cfg Config
err := xconfig.Unmarshal(&cfg,
// Load configuration from a file (optional)
xconfig.WithYAMLFile("config.yml"),
// Overlay environment values (optional)
xconfig.WithEnvironment(os.Environ()),
)
if err != nil {
slog.Error("unmarshal config", "err", err)
os.Exit(-1)
}
slog.Info("loaded config", "cfg", cfg)
}
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Unmarshal ¶
Unmarshal loads configuration into the value pointed to by v.
Configuration can be loaded from a YAML file or environment variables. If both are provided, YAML configuration is read first and environment variables are overlaid after. Default values are applied for any fields missing from both sources.
Fields can use `xconfig:"key,default"` tag for key mapping and default values. Fields can customize decoding logic by implementing the encoding.TextUnmarshaler interface.