Documentation
¶
Overview ¶
Package config provides an application configuration system.
Usage
First, config need to initialize at the beginning. if err := config.Init(); err != nil { // Handle error. }
Then to read config, just unmarshal it to a struct or map:
cfg := serverConfig Port: 8080, Name: "default", } if err := config.Unmarshal("server", &ac); err != nil { // handle error }
Configuration Source ¶
It loads configuration from the following sources. Each item takes precedence over the item below it:
- command line flag if it's defined like below: flag.String("foo.bar", "default value", "config `bar`")
- environment variables which matches the following format: prefix + "_" + the key name in ALL CAPS. For example, FOO_BAR is the name of environment variable to foo.bar.
- config file specified by WithFile and WithFS.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Unmarshal ¶
Unmarshal unmarshalls the config with prefix into a (embedded) struct pointed to by target.
It also supports unmarshaling values which uses mapstructure tags by default. See https://github.com/mitchellh/mapstructure.
Example ¶
package main import ( "fmt" "os" "github.com/ktong/nilgo/config" ) func main() { _ = os.Setenv("SOURCE", "env") defer os.Clearenv() _ = config.Init() var c struct { Source string } _ = config.Unmarshal("", &c) fmt.Println(c.Source) }
Output: env
Types ¶
type Option ¶
type Option func(*options)
Option configures how it loads application configuration.
func WithFile ¶
WithFile explicitly defines the path, name of the config file.
Example ¶
package main import ( "fmt" "testing/fstest" "github.com/ktong/nilgo/config" ) func main() { mapFS := fstest.MapFS{ "config.yaml": { Data: []byte("file:\n source: embed"), }, } _ = config.Init( config.WithFile("config.yaml"), config.WithFS(mapFS), ) var source string _ = config.Unmarshal("file.source", &source) fmt.Println(source) }
Output: embed
Click to show internal directories.
Click to hide internal directories.