Documentation
¶
Overview ¶
Package aconfig provides simple but still powerful config loader.
It can read configuration from different sources, like defaults, files, environment variables, console flag parameters.
Defaults are defined in structure tags (`default` tag). For files JSON, YAML, TOML and .Env are supported.
Environment variables and flag parameters can have an optional prefix to separate them from other entries.
Also, aconfig is dependency-free, file decoders are used as separate modules (submodules to be exact) and are added to your go.mod only when used.
Loader configuration (`Config` type) has different ways to configure loader, to skip some sources, define prefixes, fail on unknown params.
Example (Defaults) ¶
Just load defaults from struct definition.
package main
import (
"fmt"
"log"
"github.com/cristalhq/aconfig"
)
type MyConfig struct {
HTTPPort int `default:"1111" usage:"just a number"`
Auth struct {
User string `default:"def-user" usage:"your user"`
Pass string `default:"def-pass" usage:"make it strong"`
}
}
func main() {
var cfg MyConfig
loader := aconfig.LoaderFor(&cfg, aconfig.Config{
SkipFiles: true,
SkipEnv: true,
SkipFlags: true,
})
if err := loader.Load(); err != nil {
log.Panic(err)
}
fmt.Printf("HTTPPort: %v\n", cfg.HTTPPort)
fmt.Printf("Auth.User: %v\n", cfg.Auth.User)
fmt.Printf("Auth.Pass: %v\n", cfg.Auth.Pass)
}
Output: HTTPPort: 1111 Auth.User: def-user Auth.Pass: def-pass
Example (Env) ¶
Load defaults from struct definition and overwrite with a file. And then overwrite with environment variables.
package main
import (
"fmt"
"log"
"os"
"github.com/cristalhq/aconfig"
)
type MyConfig struct {
HTTPPort int `default:"1111" usage:"just a number"`
Auth struct {
User string `default:"def-user" usage:"your user"`
Pass string `default:"def-pass" usage:"make it strong"`
}
}
func main() {
os.Setenv("EXAMPLE_HTTP_PORT", "3333")
os.Setenv("EXAMPLE_AUTH_USER", "env-user")
os.Setenv("EXAMPLE_AUTH_PASS", "env-pass")
defer os.Clearenv()
var cfg MyConfig
loader := aconfig.LoaderFor(&cfg, aconfig.Config{
SkipFlags: true,
EnvPrefix: "EXAMPLE",
Files: []string{"testdata/example_config.json"},
})
if err := loader.Load(); err != nil {
log.Panic(err)
}
fmt.Printf("HTTPPort: %v\n", cfg.HTTPPort)
fmt.Printf("Auth.User: %v\n", cfg.Auth.User)
fmt.Printf("Auth.Pass: %v\n", cfg.Auth.Pass)
}
Output: HTTPPort: 3333 Auth.User: env-user Auth.Pass: env-pass
Example (File) ¶
Load defaults from struct defunition and overwrite with a file.
package main
import (
"fmt"
"log"
"github.com/cristalhq/aconfig"
)
type MyConfig struct {
HTTPPort int `default:"1111" usage:"just a number"`
Auth struct {
User string `default:"def-user" usage:"your user"`
Pass string `default:"def-pass" usage:"make it strong"`
}
}
func main() {
var cfg MyConfig
loader := aconfig.LoaderFor(&cfg, aconfig.Config{
SkipEnv: true,
SkipFlags: true,
Files: []string{"testdata/example_config.json"},
})
if err := loader.Load(); err != nil {
log.Panic(err)
}
fmt.Printf("HTTPPort: %v\n", cfg.HTTPPort)
fmt.Printf("Auth.User: %v\n", cfg.Auth.User)
fmt.Printf("Auth.Pass: %v\n", cfg.Auth.Pass)
}
Output: HTTPPort: 2222 Auth.User: json-user Auth.Pass: json-pass
Example (Flag) ¶
Load defaults from struct definition and overwrite with a file. And then overwrite with environment variables. Finally read command line flags.
package main
import (
"fmt"
"log"
"os"
"github.com/cristalhq/aconfig"
)
type MyConfig struct {
HTTPPort int `default:"1111" usage:"just a number"`
Auth struct {
User string `default:"def-user" usage:"your user"`
Pass string `default:"def-pass" usage:"make it strong"`
}
}
func main() {
var cfg MyConfig
loader := aconfig.LoaderFor(&cfg, aconfig.Config{
FlagPrefix: "ex",
Files: []string{"testdata/example_config.json"},
})
flags := loader.Flags() // <- IMPORTANT: use this to define your non-config flags
flags.String("my.other.port", "1234", "debug port")
// IMPORTANT: next statement is made only to hack flag params
// to make test example work
// feel free to remove it completely during copy-paste :)
os.Args = append([]string{}, os.Args[0],
"-ex.http_port=4444",
"-ex.auth.user=flag-user",
"-ex.auth.pass=flag-pass",
)
if err := flags.Parse(os.Args[1:]); err != nil {
log.Panic(err)
}
if err := loader.Load(); err != nil {
log.Panic(err)
}
fmt.Printf("HTTPPort: %v\n", cfg.HTTPPort)
fmt.Printf("Auth.User: %v\n", cfg.Auth.User)
fmt.Printf("Auth.Pass: %v\n", cfg.Auth.Pass)
}
Output: HTTPPort: 4444 Auth.User: flag-user Auth.Pass: flag-pass
Example (SimpleUsage) ¶
package main
import (
"fmt"
"log"
"github.com/cristalhq/aconfig"
)
type MyConfig struct {
HTTPPort int `default:"1111" usage:"just a number"`
Auth struct {
User string `default:"def-user" usage:"your user"`
Pass string `default:"def-pass" usage:"make it strong"`
}
}
func main() {
var cfg MyConfig
loader := aconfig.LoaderFor(&cfg, aconfig.Config{
SkipDefaults: true,
SkipFiles: true,
SkipEnv: true,
SkipFlags: true,
Files: []string{"/var/opt/myapp/config.json"},
EnvPrefix: "APP",
FlagPrefix: "app",
})
if err := loader.Load(); err != nil {
log.Panic(err)
}
fmt.Printf("HTTPPort: %v\n", cfg.HTTPPort)
fmt.Printf("Auth.User: %q\n", cfg.Auth.User)
fmt.Printf("Auth.Pass: %q\n", cfg.Auth.Pass)
}
Output: HTTPPort: 0 Auth.User: "" Auth.Pass: ""
Example (WalkFields) ¶
package main
import (
"fmt"
"github.com/cristalhq/aconfig"
)
type MyConfig struct {
HTTPPort int `default:"1111" usage:"just a number"`
Auth struct {
User string `default:"def-user" usage:"your user"`
Pass string `default:"def-pass" usage:"make it strong"`
}
}
func main() {
var cfg MyConfig
loader := aconfig.LoaderFor(&cfg, aconfig.Config{
SkipFiles: true,
SkipEnv: true,
SkipFlags: true,
})
loader.WalkFields(func(f aconfig.Field) bool {
fmt.Printf("%v: %q %q %q %q\n", f.Name(), f.Tag("env"), f.Tag("flag"), f.Tag("default"), f.Tag("usage"))
return true
})
}
Output: HTTPPort: "HTTP_PORT" "http_port" "1111" "just a number" Auth.User: "USER" "user" "def-user" "your user" Auth.Pass: "PASS" "pass" "def-pass" "make it strong"
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Config ¶ added in v0.9.0
type Config struct {
// NewParser set to true enables a new and better struct parser.
// Default is false because there might be bugs.
// In the future new parser will be enabled by default.
NewParser bool
SkipDefaults bool // SkipDefaults set to true will not load config from 'default' tag.
SkipFiles bool // SkipFiles set to true will not load config from files.
SkipEnv bool // SkipEnv set to true will not load config from environment variables.
SkipFlags bool // SkipFlags set to true will not load config from flag parameters.
EnvPrefix string // EnvPrefix for environment variables.
FlagPrefix string // FlagPrefix for flag parameters.
FlagDelimiter string // FlagDelimiter for flag parameters. If not set - default is ".".
// AllFieldsRequired set to true will fail config loading if one of the fields was not set.
// File, environment, flag must provide a value for the field.
// If default is set and this option is enabled (or required tag is set) there will be an error.
AllFieldRequired bool
// AllowDuplicates set to true will not fail on duplicated names on fields (env, flag, etc...)
AllowDuplicates bool
// AllowUnknownFields set to true will not fail on unknown fields in files.
AllowUnknownFields bool
// AllowUnknownEnvs set to true will not fail on unknown environment variables ().
// When false error is returned only when EnvPrefix isn't empty.
AllowUnknownEnvs bool
// AllowUnknownFlags set to true will not fail on unknown flag parameters ().
// When false error is returned only when FlagPrefix isn't empty.
AllowUnknownFlags bool
// DontGenerateTags disables tag generation for JSON, YAML, TOML file formats.
DontGenerateTags bool
// FailOnFileNotFound will stop Loader on a first not found file from Files field in this structure.
FailOnFileNotFound bool
// FileSystem from which files will be loaded. Default is nil (OS file system).
FileSystem fs.FS
// MergeFiles set to true will collect all the entries from all the given files.
// Easy wat to cobine base.yaml with prod.yaml
MergeFiles bool
// FileFlag the name of the flag that defines the path to the configuration file passed through the CLI.
// (To make it easier to transfer the config file via flags.)
FileFlag string
// Files from which config should be loaded.
Files []string
// Envs hold the environment variable from which envs will be parsed.
// By default is nil and then os.Environ() will be used.
Envs []string
// Args hold the command-line arguments from which flags will be parsed.
// By default is nil and then os.Args will be used.
// Unless loader.Flags() will be explicitly parsed by the user.
Args []string
// FileDecoders to enable other than JSON file formats and prevent additional dependencies.
// Add required submodules to the go.mod and register them in this field.
// Example:
// FileDecoders: map[string]aconfig.FileDecoder{
// ".yaml": aconfigyaml.New(),
// ".toml": aconfigtoml.New(),
// ".env": aconfigdotenv.New(),
// }
FileDecoders map[string]FileDecoder
// SliceSeparator hold the separator for slice values. Default is ",".
SliceSeparator string
// contains filtered or unexported fields
}
Config to configure configuration loader.
type Field ¶ added in v0.4.0
type Field interface {
// Name of the field.
Name() string
// Tag returns a given tag for a field.
Tag(tag string) string
// Parent of the current node.
Parent() (Field, bool)
}
Field of the user configuration structure. Done as an interface to export less things in lib.
type FileDecoder ¶ added in v0.8.0
FileDecoder is used to read config from files. See aconfig submodules.
type Loader ¶
type Loader struct {
// contains filtered or unexported fields
}
Loader of user configuration.
func LoaderFor ¶ added in v0.2.1
LoaderFor creates a new Loader based on a given configuration structure. Supports only non-nil structures.
func (*Loader) Flags ¶ added in v0.1.2
Flags returngs flag.FlagSet to create your own flags. FlagSet name is Config.FlagPrefix and error handling is set to ContinueOnError.
func (*Loader) WalkFields ¶ added in v0.4.0
WalkFields iterates over configuration fields. Easy way to create documentation or user-friendly help.
Directories
¶
| Path | Synopsis |
|---|---|
|
aconfigdotenv
module
|
|
|
aconfighcl
module
|
|
|
aconfigtoml
module
|
|
|
aconfigyaml
module
|