Documentation
¶
Overview ¶
Package konf provides a general-purpose configuration API and abstract interfaces to back that API. Packages in the Go ecosystem can depend on this package, while callers can load configuration from whatever source is appropriate.
It defines a type, Config, which provides a method Config.Unmarshal for loading configuration under the given path into the given object.
Each Config is associated with multiple Loader(s), Which load configuration from a source, such as file, environment variables etc. There is a default Config accessible through top-level functions (such as Unmarshal and Get) that call the corresponding Config methods.
Configuration is hierarchical, and the path is a sequence of keys that separated by delimiter. The default delimiter is `.`, which makes configuration path like `parent.child.key`.
Load Configuration ¶
After creating a Config, you can load configuration from multiple Loader(s) using Config.Load. Each loader takes precedence over the loaders before it. As long as the configuration has been loaded, it can be used in following code to get or unmarshal configuration, even for loading configuration from another source. For example, it can read config file path from environment variables, and then use the file path to load configuration from file system.
Watch Changes ¶
Config.Watch watches and updates configuration when it changes, which leads Config.Unmarshal always returns latest configuration. You may use Config.OnChange to register a callback if the value of any path have been changed. It could push the change into application objects instead pulling the configuration periodically.
Index ¶
- func CredentialFormatter() func(path string, loader Loader, value any) string
- func Get[T any](path string) T
- func OnChange(onChange func(), paths ...string)
- func SetDefault(config *Config)
- func Unmarshal(path string, target any) error
- type Config
- func (c *Config) Exists(path []string) bool
- func (c *Config) Explain(path string, opts ...ExplainOption) string
- func (c *Config) Load(loader Loader) error
- func (c *Config) OnChange(onChange func(*Config), paths ...string)
- func (c *Config) Unmarshal(path string, target any) error
- func (c *Config) Watch(ctx context.Context) error
- type DecodeHook
- type ExplainOption
- type Loader
- type Option
- type Watcher
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CredentialFormatter ¶ added in v0.5.0
CredentialFormatter provides the value formatter which blurs sensitive information.
func Get ¶
Get retrieves the value under the given path from the default Config. It returns the zero value of the expected type if there is an error. The path is case-insensitive.
Example ¶
package main
import (
"embed"
"fmt"
"github.com/nil-go/konf"
"github.com/nil-go/konf/provider/env"
kfs "github.com/nil-go/konf/provider/fs"
)
func main() {
ExampleSetDefault()
fmt.Print(konf.Get[string]("server.host"))
}
//go:embed testdata
var testdata embed.FS
func ExampleSetDefault() {
config := konf.New()
if err := config.Load(kfs.New(testdata, "testdata/config.json")); err != nil {
panic(err)
}
if err := config.Load(env.New(env.WithPrefix("server"))); err != nil {
panic(err)
}
konf.SetDefault(config)
}
Output: example.com
func OnChange ¶
func OnChange(onChange func(), paths ...string)
OnChange registers a callback function that is executed when the value of any given path in the default Config changes. The paths are case-insensitive.
The onChange function must be non-blocking and usually completes instantly. If it requires a long time to complete, it should be executed in a separate goroutine.
This method is concurrency-safe. It panics if onChange is nil.
func SetDefault ¶
func SetDefault(config *Config)
SetDefault sets the given Config as the default Config. After this call, the konf package's top functions (e.g. konf.Get) will interact with the given Config.
Example ¶
package main
import (
"embed"
"github.com/nil-go/konf"
"github.com/nil-go/konf/provider/env"
kfs "github.com/nil-go/konf/provider/fs"
)
//go:embed testdata
var testdata embed.FS
func main() {
config := konf.New()
if err := config.Load(kfs.New(testdata, "testdata/config.json")); err != nil {
// Handle error here.
panic(err)
}
if err := config.Load(env.New(env.WithPrefix("server"))); err != nil {
// Handle error here.
panic(err)
}
konf.SetDefault(config)
}
Output:
func Unmarshal ¶
Unmarshal reads configuration under the given path from the default Config and decodes it into the given object pointed to by target. The path is case-insensitive.
Example ¶
package main
import (
"embed"
"fmt"
"github.com/nil-go/konf"
"github.com/nil-go/konf/provider/env"
kfs "github.com/nil-go/konf/provider/fs"
)
func main() {
ExampleSetDefault()
cfg := struct {
Host string
Port int
}{
Host: "localhost",
Port: 8080,
}
if err := konf.Unmarshal("server", &cfg); err != nil {
// Handle error here.
panic(err)
}
fmt.Printf("%s:%d\n", cfg.Host, cfg.Port)
}
//go:embed testdata
var testdata embed.FS
func ExampleSetDefault() {
config := konf.New()
if err := config.Load(kfs.New(testdata, "testdata/config.json")); err != nil {
panic(err)
}
if err := config.Load(env.New(env.WithPrefix("server"))); err != nil {
panic(err)
}
konf.SetDefault(config)
}
Output: example.com:8080
Types ¶
type Config ¶
type Config struct {
// contains filtered or unexported fields
}
Config reads configuration from appropriate sources.
To create a new Config, call New.
func (*Config) Exists ¶
Exists tests if the given path exist in the configuration.
It's used by the loader to check if the configuration has been set by other loaders.
func (*Config) Explain ¶
func (c *Config) Explain(path string, opts ...ExplainOption) string
Explain provides information about how Config resolve each value from loaders for the given path. The path is case-insensitive.
If there are sensitive information (e.g. password, secret) which should not be exposed, you can use WithValueFormatter to pass a value formatter to blur the information. By default, it uses CredentialFormatter to blur sensitive information.
func (*Config) Load ¶
Load loads configuration from the given loader. Each loader takes precedence over the loaders before it.
This method can be called multiple times but it is not concurrency-safe. It panics if loader is nil.
func (*Config) OnChange ¶
OnChange registers a callback function that is executed when the value of any given path in the Config changes. It requires Config.Watch has been called first. The paths are case-insensitive.
The onChange function must be non-blocking and usually completes instantly. If it requires a long time to complete, it should be executed in a separate goroutine.
This method is concurrency-safe. It panics if onChange is nil.
func (*Config) Unmarshal ¶
Unmarshal reads configuration under the given path from the Config and decodes it into the given object pointed to by target. The path is case-insensitive.
func (*Config) Watch ¶
Watch watches and updates configuration when it changes. It blocks until ctx is done, or the service returns an error. WARNING: All loaders passed in Load after calling Watch do not get watched.
It only can be called once. Call after first has no effects. It panics if ctx is nil.
type DecodeHook ¶ added in v0.5.0
type DecodeHook any
type ExplainOption ¶
type ExplainOption func(*explainOptions)
ExplainOption configures Config.Explain with specific options.
func WithValueFormatter ¶
func WithValueFormatter(valueFormatter func(string, Loader, any) string) ExplainOption
WithValueFormatter provides the value formatter for Config.Explain. It's for hiding sensitive information (e.g. password, secret) which should not be exposed.
By default, it uses fmt.Sprint to format the value.
type Loader ¶
Loader is the interface that wraps the Load method.
Load loads the latest configuration and returns it as a nested map[string]any. The keys in the returned map should be case-insensitive to avoid random overriding. The keys should be nested like `{parent: {child: {key: 1}}}`.
type Option ¶
type Option func(*options)
Option configures a Config with specific options.
func WithDecodeHook ¶
func WithDecodeHook(decodeHook DecodeHook) Option
WithDecodeHook provides the decode hook for decoding. The decode hook is a function that can transform or customize how values are decoded.
By default, it composes StringToTimeDurationHookFunc, StringToSliceHookFunc(",") and TextUnmarshallerHookFunc.
func WithDelimiter ¶
WithDelimiter provides the delimiter used when specifying config paths. The delimiter is used to separate keys in the path.
For example, with the default delimiter `.`, a config path might look like `parent.child.key`.
func WithLogHandler ¶
WithLogHandler provides the slog.Handler for logs from watch.
By default, it uses handler from slog.Default().
func WithTagName ¶
WithTagName provides the tag name that reads for field names. The tag name is used when decoding configuration into structs.
For example, with the default tag name `konf`, it would look for `konf` tags on struct fields.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
notifier
|
|
|
azservicebus
module
|
|
|
pubsub
module
|
|
|
sns
module
|
|
|
provider
|
|
|
env
Package env loads configuration from environment variables.
|
Package env loads configuration from environment variables. |
|
flag
Package flag loads configuration from flags defined by flag.
|
Package flag loads configuration from flags defined by flag. |
|
fs
Package fs loads configuration from file system.
|
Package fs loads configuration from file system. |
|
appconfig
module
|
|
|
azappconfig
module
|
|
|
azblob
module
|
|
|
file
module
|
|
|
gcs
module
|
|
|
parameterstore
module
|
|
|
pflag
module
|
|
|
s3
module
|
|
|
secretmanager
module
|