config

package module
v2.2.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 13, 2024 License: MIT Imports: 26 Imported by: 185

README

Config

GitHub go.mod Go version Codacy Badge Build Status Actions Status Coverage Status Go Report Card Go Reference

config - Simple, full-featured Go application configuration management tool library.

中文说明

Features

  • Support multi format: JSON(default), JSON5, INI, Properties, YAML, TOML, HCL, ENV, Flags
    • JSON content support comments. will auto clear comments
    • Other drivers are used on demand, not used will not be loaded into the application.
      • Possibility to add custom driver for your specific format
  • Support multi-file and multi-data loading
  • Support for loading configuration from system ENV
  • Support for loading configuration data from remote URLs
  • Support for setting configuration data from command line(flags)
  • Support listen and fire events on config data changed.
    • allow events: set.value, set.data, load.data, clean.data, reload.data
  • Support data overlay and merge, automatically load by key when loading multiple copies of data
  • Support for binding all or part of the configuration data to the structure
    • Support init default value by struct tag default:"def_value"
    • Support init default value from ENV default:"${APP_ENV | dev}"
  • Support get sub value by key-path, like map.key arr.2
  • Support parse ENV name and allow with default value. like envKey: ${SHELL|/bin/bash} -> envKey: /bin/zsh
  • Generic API: Get Int Uint Int64 Float String Bool Ints IntMap Strings StringMap ...
  • Complete unit test(code coverage > 95%)

Only use INI

If you just want to use INI for simple config management, recommended use gookit/ini

Load dotenv file

On gookit/ini: Provide a sub-package dotenv that supports importing data from files (eg .env) to ENV

go get github.com/gookit/ini/v2/dotenv

GoDoc

Install

go get github.com/gookit/config/v2

Usage

Here using the yaml format as an example(testdata/yml_other.yml):

name: app2
debug: false
baseKey: value2
shell: ${SHELL}
envKey1: ${NotExist|defValue}

map1:
    key: val2
    key2: val20

arr1:
    - val1
    - val21
Load data

examples code please see _examples/yaml.go:

package main

import (
    "github.com/gookit/config/v2"
    "github.com/gookit/config/v2/yaml"
)

// go run ./examples/yaml.go
func main() {
	// config.ParseEnv: will parse env var in string value. eg: shell: ${SHELL}
	config.WithOptions(config.ParseEnv)

	// add driver for support yaml content
	config.AddDriver(yaml.Driver)

	err := config.LoadFiles("testdata/yml_base.yml")
	if err != nil {
		panic(err)
	}

	// load more files
	err = config.LoadFiles("testdata/yml_other.yml")
	// can also load multi at once
	// err := config.LoadFiles("testdata/yml_base.yml", "testdata/yml_other.yml")
	if err != nil {
		panic(err)
	}

	// fmt.Printf("config data: \n %#v\n", config.Data())
}

Usage tips:

  • More extra options can be added using WithOptions(). For example: ParseEnv, ParseDefault
  • You can use AddDriver() to add the required format driver (json is loaded by default, no need to add)
  • The configuration data can then be loaded using LoadFiles() LoadStrings() etc.
    • You can pass in multiple files or call multiple times
    • Data loaded multiple times will be automatically merged by key

Bind Structure

Note: The default binding mapping tag of a structure is mapstructure, which can be changed by setting the decoder's option options.DecoderConfig.TagName

type User struct {
    Age  int  `mapstructure:"age"`
    Key  string `mapstructure:"key"`
    UserName  string `mapstructure:"user_name"`
    Tags []int  `mapstructure:"tags"`
}

user := User{}
err = config.BindStruct("user", &user)

fmt.Println(user.UserName) // inhere

Change struct tag name

config.WithOptions(func(opt *Options) {
    options.DecoderConfig.TagName = "config"
})

// use custom tag name.
type User struct {
  Age  int  `config:"age"`
  Key  string `config:"key"`
  UserName  string `config:"user_name"`
  Tags []int  `config:"tags"`
}

user := User{}
err = config.Decode(&user)

Can bind all config data to a struct:

config.Decode(&myConf)
// can also
config.BindStruct("", &myConf)

config.MapOnExists like BindStruct,but map binding only if key exists

Direct read data
  • Get integer
age := config.Int("age")
fmt.Print(age) // 100
  • Get bool
val := config.Bool("debug")
fmt.Print(val) // true
  • Get string
name := config.String("name")
fmt.Print(name) // inhere
  • Get strings(slice)
arr1 := config.Strings("arr1")
fmt.Printf("%#v", arr1) // []string{"val1", "val21"}
  • Get string map
val := config.StringMap("map1")
fmt.Printf("%#v",val) // map[string]string{"key":"val2", "key2":"val20"}
  • Value contains ENV var
value := config.String("shell")
fmt.Print(value) // "/bin/zsh"
  • Get value by key path
// from array
value := config.String("arr1.0")
fmt.Print(value) // "val1"

// from map
value := config.String("map1.key")
fmt.Print(value) // "val2"
  • Setting new value
// set value
config.Set("name", "new name")
name = config.String("name")
fmt.Print(name) // "new name"

Load from flags

Support simple flags parameter parsing, loading

// flags like: --name inhere --env dev --age 99 --debug

// load flag info
keys := []string{"name", "env", "age:int" "debug:bool"}
err := config.LoadFlags(keys)

// read
config.String("name") // "inhere"
config.String("env") // "dev"
config.Int("age") // 99
config.Bool("debug") // true

Load from ENV

// os env: APP_NAME=config APP_DEBUG=true
// load ENV info
config.LoadOSEnvs(map[string]string{"APP_NAME": "app_name", "APP_DEBUG": "app_debug"})

// read
config.Bool("app_debug") // true
config.String("app_name") // "config"

New config instance

You can create custom config instance

// create new instance, will auto register JSON driver
myConf := config.New("my-conf")

// create empty instance
myConf := config.NewEmpty("my-conf")

// create and with some options
myConf := config.NewWithOptions("my-conf", config.ParseEnv, config.ReadOnly)

Listen config change

Now, you can add a hook func for listen config data change. then, you can do something like: write data to file

Add hook func on create config:

hookFn := func(event string, c *Config) {
    fmt.Println("fire the:", event)
}

c := NewWithOptions("test", config.WithHookFunc(hookFn))
// for global config
config.WithOptions(config.WithHookFunc(hookFn))

After that, when calling LoadXXX, Set, SetData, ClearData methods, it will output:

fire the: load.data
fire the: set.value
fire the: set.data
fire the: clean.data
Watch loaded config files

To listen for changes to loaded config files, and reload the config when it changes, you need to use the https://github.com/fsnotify/fsnotify library. For usage, please refer to the example ./_example/watch_file.go

Also, you need to listen to the reload.data event:

config.WithOptions(config.WithHookFunc(func(event string, c *config.Config) {
    if event == config.OnReloadData {
        fmt.Println("config reloaded, you can do something ....")
    }
}))

When the configuration changes, you can do related things, for example: rebind the configuration to your struct.

Dump config data

Can use config.DumpTo() export the configuration data to the specified writer, such as: buffer,file

Dump to JSON file

buf := new(bytes.Buffer)

_, err := config.DumpTo(buf, config.JSON)
ioutil.WriteFile("my-config.json", buf.Bytes(), 0755)

Dump pretty JSON

You can set the default var JSONMarshalIndent or custom a new JSON driver.

config.JSONMarshalIndent = "    "

Dump to YAML file

_, err := config.DumpTo(buf, config.YAML)
ioutil.WriteFile("my-config.yaml", buf.Bytes(), 0755)

Available options

// Options config options
type Options struct {
	// parse env in string value. like: "${EnvName}" "${EnvName|default}"
	ParseEnv bool
    // ParseTime parses a duration string to time.Duration
    // eg: 10s, 2m
    ParseTime bool
	// config is readonly. default is False
	Readonly bool
	// enable config data cache. default is False
	EnableCache bool
	// parse key, allow find value by key path. default is True eg: 'key.sub' will find `map[key]sub`
	ParseKey bool
	// the delimiter char for split key path, if `FindByPath=true`. default is '.'
	Delimiter byte
	// default write format
	DumpFormat string
	// default input format
	ReadFormat string
	// DecoderConfig setting for binding data to struct
	DecoderConfig *mapstructure.DecoderConfig
	// HookFunc on data changed.
	HookFunc HookFunc
	// ParseDefault tag on binding data to struct. tag: default
	ParseDefault bool
}

Examples for set options:

config.WithOptions(config.WithTagName("mytag"))
config.WithOptions(func(opt *Options) {
    opt.SetTagNames("config")
})
Options: Parse default

Support parse default value by struct tag default

// add option: config.ParseDefault
c := config.New("test").WithOptions(config.ParseDefault)

// only set name
c.SetData(map[string]any{
    "name": "inhere",
})

// age load from default tag
type User struct {
    Age  int `default:"30"`
    Name string
    Tags []int
}

user := &User{}
goutil.MustOk(c.Decode(user))
dump.Println(user)

Output:

&config_test.User {
  Age: int(30),
  Name: string("inhere"), #len=6
  Tags: []int [ #len=0
  ],
},

API Methods Refer

Load Config
  • LoadOSEnvs(nameToKeyMap map[string]string) Load data from os ENV
  • LoadData(dataSource ...any) (err error) Load from struts or maps
  • LoadFlags(keys []string) (err error) Load from CLI flags
  • LoadExists(sourceFiles ...string) (err error)
  • LoadFiles(sourceFiles ...string) (err error)
  • LoadFromDir(dirPath, format string) (err error) Load custom format files from the given directory, the file name will be used as the key
  • LoadRemote(format, url string) (err error)
  • LoadSources(format string, src []byte, more ...[]byte) (err error)
  • LoadStrings(format string, str string, more ...string) (err error)
  • LoadFilesByFormat(format string, sourceFiles ...string) (err error)
  • LoadExistsByFormat(format string, sourceFiles ...string) error
Getting Values
  • Bool(key string, defVal ...bool) bool
  • Int(key string, defVal ...int) int
  • Uint(key string, defVal ...uint) uint
  • Int64(key string, defVal ...int64) int64
  • Ints(key string) (arr []int)
  • IntMap(key string) (mp map[string]int)
  • Float(key string, defVal ...float64) float64
  • String(key string, defVal ...string) string
  • Strings(key string) (arr []string)
  • SubDataMap(key string) maputi.Data
  • StringMap(key string) (mp map[string]string)
  • Get(key string, findByPath ...bool) (value any)

Mapping data to struct:

  • Decode(dst any) error
  • BindStruct(key string, dst any) error
  • MapOnExists(key string, dst any) error
Setting Values
  • Set(key string, val any, setByPath ...bool) (err error)
Useful Methods
  • Getenv(name string, defVal ...string) (val string)
  • AddDriver(driver Driver)
  • Data() map[string]any
  • SetData(data map[string]any) set data to override the Config.Data
  • Exists(key string, findByPath ...bool) bool
  • DumpTo(out io.Writer, format string) (n int64, err error)

Run Tests

go test -cover
// contains all sub-folder
go test -cover ./...

Projects using config

Check out these projects, which use https://github.com/gookit/config :

Gookit packages

  • gookit/ini Go config management, use INI files
  • gookit/rux Simple and fast request router for golang HTTP
  • gookit/gcli build CLI application, tool library, running CLI commands
  • gookit/event Lightweight event manager and dispatcher implements by Go
  • gookit/cache Generic cache use and cache manager for golang. support File, Memory, Redis, Memcached.
  • gookit/config Go config management. support JSON, YAML, TOML, INI, HCL, ENV and Flags
  • gookit/color A command-line color library with true color support, universal API methods and Windows support
  • gookit/filter Provide filtering, sanitizing, and conversion of golang data
  • gookit/validate Use for data validation and filtering. support Map, Struct, Form data
  • gookit/goutil Some utils for the Go: string, array/slice, map, format, cli, env, filesystem, test and more
  • More, please see https://github.com/gookit

See also

License

MIT

Documentation

Overview

Package config is a go config management implement. support YAML,TOML,JSON,INI,HCL format.

Source code and other details for the project are available at GitHub:

https://github.com/gookit/config

JSON format content example:

{
	"name": "app",
	"debug": false,
	"baseKey": "value",
	"age": 123,
	"envKey": "${SHELL}",
	"envKey1": "${NotExist|defValue}",
	"map1": {
		"key": "val",
		"key1": "val1",
		"key2": "val2"
	},
	"arr1": [
		"val",
		"val1",
		"val2"
	],
	"lang": {
		"dir": "res/lang",
		"defLang": "en",
		"allowed": {
			"en": "val",
			"zh-CN": "val2"
		}
	}
}

Usage please see example(more example please see examples folder in the lib):

Example
// WithOptions(ParseEnv)

// use yaml github.com/gookit/config/yamlv3
// AddDriver(Yaml, yamlv3.Driver)
// use toml github.com/gookit/config/toml
// AddDriver(Toml, toml.Driver)
// use toml github.com/gookit/config/hcl
// AddDriver(Hcl, hcl.Driver)

err := LoadFiles("testdata/json_base.json")
if err != nil {
	panic(err)
}

// fmt.Printf("config data: \n %#v\n", Data())

err = LoadFiles("testdata/json_other.json")
// LoadFiles("testdata/json_base.json", "testdata/json_other.json")
if err != nil {
	panic(err)
}

// load from string
err = LoadSources(JSON, []byte(jsonStr))
if err != nil {
	panic(err)
}

// fmt.Printf("config data: \n %#v\n", Data())
fmt.Print("get config example:\n")

name := String("name")
fmt.Printf("- get string\n val: %v\n", name)

arr1 := Strings("arr1")
fmt.Printf("- get array\n val: %#v\n", arr1)

val0 := String("arr1.0")
fmt.Printf("- get sub-value by path 'arr.index'\n val: %#v\n", val0)

map1 := StringMap("map1")
fmt.Printf("- get map\n val: %#v\n", map1)

val0 = String("map1.key")
fmt.Printf("- get sub-value by path 'map.key'\n val: %#v\n", val0)

// can parse env name(ParseEnv: true)
fmt.Printf("get env 'envKey' val: %s\n", String("envKey", ""))
fmt.Printf("get env 'envKey1' val: %s\n", String("envKey1", ""))

// set value
_ = Set("name", "new name")
name = String("name")
fmt.Printf("- set string\n val: %v\n", name)

// if you want export config data
// buf := new(bytes.Buffer)
// _, err = config.DumpTo(buf, config.JSON)
// if err != nil {
// 	panic(err)
// }
// fmt.Printf("export config:\n%s", buf.String())

// Out:
// get config example:
// - get string
//  val: app
// - get array
//  val: []string{"val", "val1", "val2"}
// - get sub-value by path 'arr.index'
//  val: "val"
// - get map
//  val: map[string]string{"key":"val", "key1":"val1", "key2":"val2"}
// - get sub-value by path 'map.key'
//  val: "val"
// get env 'envKey' val: /bin/zsh
// get env 'envKey1' val: defValue
// - set string
//  val: new name
Output:

Example (ExportConfig)
// Notice: before dump please set driver encoder
// SetEncoder(Yaml, yaml.Encoder)

ClearAll()
// load from string
err := LoadStrings(JSON, `{
"name": "app",
"age": 34
}`)
if err != nil {
	panic(err)
}

buf := new(bytes.Buffer)
_, err = DumpTo(buf, JSON)
if err != nil {
	panic(err)
}

fmt.Printf("%s", buf.String())
Output:

{"age":34,"name":"app"}

Index

Examples

Constants

View Source
const (
	Ini  = "ini"
	Hcl  = "hcl"
	Yml  = "yml"
	JSON = "json"
	Yaml = "yaml"
	Toml = "toml"
	Prop = "properties"
)

There are supported config format

View Source
const (
	OnSetValue   = "set.value"
	OnSetData    = "set.data"
	OnLoadData   = "load.data"
	OnReloadData = "reload.data"
	OnCleanData  = "clean.data"
)

there are some event names for config data changed.

Variables

View Source
var (
	// JSONAllowComments support write comments on json file.
	JSONAllowComments = true

	// JSONMarshalIndent if not empty, will use json.MarshalIndent for encode data.
	//
	// Deprecated: please use JSONDriver.MarshalIndent
	JSONMarshalIndent string
)
View Source
var (
	ErrReadonly   = errors.New("the config instance in 'readonly' mode")
	ErrKeyIsEmpty = errors.New("the config key is cannot be empty")
	ErrNotFound   = errors.New("this key does not exist in the config")
)

some common errors definitions

View Source
var JSONDriver = &jsonDriver{
	driverName:    JSON,
	ClearComments: JSONAllowComments,
	MarshalIndent: JSONMarshalIndent,
}

JSONDriver instance fot json

Functions

func AddAlias added in v2.2.2

func AddAlias(format, alias string)

AddAlias add alias for a format(driver name)

func AddDriver

func AddDriver(driver Driver)

AddDriver set a decoder and encoder driver for a format.

func BindStruct added in v2.0.11

func BindStruct(key string, dst any) error

BindStruct alias method of the 'Structure'

func Bool

func Bool(key string, defVal ...bool) bool

Bool get a bool value, if not found return default value

func ClearAll

func ClearAll()

ClearAll data and caches

func Data

func Data() map[string]any

Data return all config data

func Decode added in v2.1.4

func Decode(dst any) error

Decode all config data to the dst ptr

Usage:

myConf := &MyConf{}
config.Decode(myConf)

func Delimiter added in v2.0.12

func Delimiter(sep byte) func(*Options)

Delimiter set delimiter char

func DumpTo

func DumpTo(out io.Writer, format string) (int64, error)

DumpTo a writer and use format

func Duration added in v2.1.8

func Duration(key string, defVal ...time.Duration) time.Duration

Duration get a time.Duration type value. if not found return default value

func EnableCache

func EnableCache(opts *Options)

EnableCache set readonly

func Exists

func Exists(key string, findByPath ...bool) bool

Exists key exists check

func Float

func Float(key string, defVal ...float64) float64

Float get a float64 value, if not found return default value

func Get

func Get(key string, findByPath ...bool) any

Get config value by key string, support get sub-value by key path(eg. 'map.key'),

  • ok is true, find value from config
  • ok is false, not found or error

func GetEnv

func GetEnv(name string, defVal ...string) (val string)

GetEnv get os ENV value by name

func GetValue

func GetValue(key string, findByPath ...bool) (any, bool)

GetValue get value by given key string.

func Getenv added in v2.0.10

func Getenv(name string, defVal ...string) (val string)

Getenv get os ENV value by name. like os.Getenv, but support default value

Notice: - Key is not case-sensitive when getting

func Int

func Int(key string, defVal ...int) int

Int get an int by key

func Int64

func Int64(key string, defVal ...int64) int64

Int64 get a int value, if not found return default value

func IntMap

func IntMap(key string) map[string]int

IntMap get config data as a map[string]int

func Ints

func Ints(key string) []int

Ints get config data as an int slice/array

func Keys added in v2.2.0

func Keys() []string

Keys return all config data

func LoadData

func LoadData(dataSource ...any) error

LoadData load one or multi data

func LoadExists

func LoadExists(sourceFiles ...string) error

LoadExists load one or multi files, will ignore not exist

Usage:

config.LoadExists(file1, file2, ...)

func LoadExistsByFormat added in v2.0.26

func LoadExistsByFormat(format string, configFiles ...string) error

LoadExistsByFormat load one or multi files by give format, will fire OnLoadData event

func LoadFiles

func LoadFiles(sourceFiles ...string) error

LoadFiles load one or multi files, will fire OnLoadData event

Usage:

config.LoadFiles(file1, file2, ...)

func LoadFilesByFormat added in v2.0.26

func LoadFilesByFormat(format string, configFiles ...string) error

LoadFilesByFormat load one or multi config files by give format, will fire OnLoadData event

func LoadFlags

func LoadFlags(keys []string) error

LoadFlags load data from cli flags

func LoadFromDir added in v2.1.8

func LoadFromDir(dirPath, format string, loFns ...LoadOptFn) error

LoadFromDir Load custom format files from the given directory, the file name will be used as the key.

Example:

// file: /somedir/task.json
LoadFromDir("/somedir", "json")

// after load
Config.data = map[string]any{"task": file data}

func LoadOSEnv deprecated

func LoadOSEnv(keys []string, keyToLower bool)

LoadOSEnv load data from OS ENV

Deprecated: please use LoadOSEnvs()

func LoadOSEnvs added in v2.1.7

func LoadOSEnvs(nameToKeyMap map[string]string)

LoadOSEnvs load data from OS ENVs. format: {ENV_NAME: config_key}

func LoadRemote

func LoadRemote(format, url string) error

LoadRemote load config data from remote URL.

func LoadSources

func LoadSources(format string, src []byte, more ...[]byte) error

LoadSources load one or multi byte data

func LoadStrings

func LoadStrings(format string, str string, more ...string) error

LoadStrings load one or multi string

func MapOnExists added in v2.1.0

func MapOnExists(key string, dst any) error

MapOnExists mapping data to the dst structure only on key exists.

func MapStruct

func MapStruct(key string, dst any) error

MapStruct alias method of the 'Structure'

Usage:

dbInfo := &Db{}
config.MapStruct("db", dbInfo)

func MustString added in v2.2.0

func MustString(key string) string

MustString get a string by key, will panic on empty or not exists

func ParseDefault added in v2.1.4

func ParseDefault(opts *Options)

ParseDefault tag value on binding data to struct.

func ParseEnv

func ParseEnv(opts *Options)

ParseEnv set parse env value

func ParseTime added in v2.1.3

func ParseTime(opts *Options)

ParseTime set parse time string.

func Readonly

func Readonly(opts *Options)

Readonly set readonly

func ReloadFiles added in v2.1.7

func ReloadFiles() error

ReloadFiles reload config data use loaded files

func Reset added in v2.1.4

func Reset()

Reset data and caches

func SaveFileOnSet added in v2.1.3

func SaveFileOnSet(fileName string, format string) func(options *Options)

SaveFileOnSet set hook func, will panic on save error

func Set

func Set(key string, val any, setByPath ...bool) error

Set val by key

func SetData added in v2.0.16

func SetData(data map[string]any)

SetData for override the Config.Data

func SetDecoder deprecated

func SetDecoder(format string, decoder Decoder)

SetDecoder add/set a format decoder

Deprecated: please use driver instead

func SetEncoder deprecated

func SetEncoder(format string, encoder Encoder)

SetEncoder set a encoder for the format

Deprecated: please use driver instead

func String

func String(key string, defVal ...string) string

String get a string by key

func StringMap

func StringMap(key string) map[string]string

StringMap get config data as a map[string]string

func Strings

func Strings(key string) []string

Strings get strings by key

func StringsBySplit added in v2.2.0

func StringsBySplit(key, sep string) []string

StringsBySplit get []string by split a string value.

func Sub added in v2.2.4

func Sub(key string) map[string]any

Sub return sub config data by key

func SubDataMap added in v2.1.8

func SubDataMap(key string) maputil.Map

SubDataMap get sub config data as maputil.Map

func Uint

func Uint(key string, defVal ...uint) uint

Uint get a uint value, if not found return default value

func ValDecodeHookFunc added in v2.1.3

func ValDecodeHookFunc(parseEnv, parseTime bool) mapstructure.DecodeHookFunc

ValDecodeHookFunc returns a mapstructure.DecodeHookFunc that parse ENV var, and more custom parse

func WithDriver added in v2.1.5

func WithDriver(drivers ...Driver)

WithDriver set multi drivers at once.

func WithHookFunc added in v2.1.0

func WithHookFunc(fn HookFunc) func(*Options)

WithHookFunc set hook func

func WithOptions

func WithOptions(opts ...OptionFn)

WithOptions with options

func WithTagName added in v2.1.5

func WithTagName(tagName string) func(*Options)

WithTagName set tag name for export to struct

func WriteTo

func WriteTo(out io.Writer) (int64, error)

WriteTo a writer

Types

type Config

type Config struct {
	// contains filtered or unexported fields
}

Config structure definition

func Default

func Default() *Config

Default get the default instance

func New

func New(name string, opts ...OptionFn) *Config

New config instance with custom options, default with JSON driver

func NewEmpty

func NewEmpty(name string, opts ...OptionFn) *Config

NewEmpty create config instance with custom options

func NewWith added in v2.0.22

func NewWith(name string, fn func(c *Config)) *Config

NewWith create config instance, and you can call some init func

func NewWithOptions

func NewWithOptions(name string, opts ...OptionFn) *Config

NewWithOptions config instance. alias of New()

func (*Config) AddAlias added in v2.2.2

func (c *Config) AddAlias(format, alias string)

AddAlias add alias for a format(driver name)

Example:

config.AddAlias("ini", "conf")

func (*Config) AddDriver

func (c *Config) AddDriver(driver Driver)

AddDriver set a decoder and encoder driver for a format.

func (*Config) AliasMap added in v2.2.2

func (c *Config) AliasMap() map[string]string

AliasMap get alias map

func (*Config) BindStruct added in v2.0.11

func (c *Config) BindStruct(key string, dst any) error

BindStruct alias method of the 'Structure'

func (*Config) Bool

func (c *Config) Bool(key string, defVal ...bool) (value bool)

Bool looks up a value for a key in this section and attempts to parse that value as a boolean, along with a boolean result similar to a map lookup.

of following(case insensitive):

  • true
  • yes
  • false
  • no
  • 1
  • 0

The `ok` boolean will be false in the event that the value could not be parsed as a bool

func (*Config) ClearAll

func (c *Config) ClearAll()

ClearAll data and caches

func (*Config) ClearCaches

func (c *Config) ClearCaches()

ClearCaches clear caches

func (*Config) ClearData

func (c *Config) ClearData()

ClearData clear data

func (*Config) Data

func (c *Config) Data() map[string]any

Data get all config data.

Note: will don't apply any options, like ParseEnv

func (*Config) Decode added in v2.1.4

func (c *Config) Decode(dst any) error

Decode all config data to the dst ptr.

It's equals:

c.Structure("", dst)

func (*Config) DelDriver

func (c *Config) DelDriver(format string)

DelDriver delete driver of the format

func (*Config) DriverNames added in v2.1.1

func (c *Config) DriverNames() []string

DriverNames get loaded driver names

func (*Config) DumpTo

func (c *Config) DumpTo(out io.Writer, format string) (n int64, err error)

DumpTo use the format(json,yaml,toml) dump config data to a writer

func (*Config) DumpToFile added in v2.1.3

func (c *Config) DumpToFile(fileName string, format string) (err error)

DumpToFile use the format(json,yaml,toml) dump config data to a writer

func (*Config) Duration added in v2.1.8

func (c *Config) Duration(key string, defVal ...time.Duration) time.Duration

Duration get a time.Duration type value. if not found return default value

func (*Config) Error

func (c *Config) Error() error

Error get last error, will clear after read.

func (*Config) Exists

func (c *Config) Exists(key string, findByPath ...bool) (ok bool)

Exists key exists check

func (*Config) Float

func (c *Config) Float(key string, defVal ...float64) (value float64)

Float get a float64 by key

func (*Config) Get

func (c *Config) Get(key string, findByPath ...bool) any

Get config value by key

func (*Config) GetValue

func (c *Config) GetValue(key string, findByPath ...bool) (value any, ok bool)

GetValue get value by given key string.

func (*Config) HasDecoder

func (c *Config) HasDecoder(format string) bool

HasDecoder has decoder

func (*Config) HasEncoder

func (c *Config) HasEncoder(format string) bool

HasEncoder has encoder

func (*Config) Int

func (c *Config) Int(key string, defVal ...int) (value int)

Int get a int value, if not found return default value

func (*Config) Int64

func (c *Config) Int64(key string, defVal ...int64) (value int64)

Int64 get a int value, if not found return default value

func (*Config) IntMap

func (c *Config) IntMap(key string) (mp map[string]int)

IntMap get config data as a map[string]int

func (*Config) Ints

func (c *Config) Ints(key string) (arr []int)

Ints get config data as an int slice/array

func (*Config) IsEmpty

func (c *Config) IsEmpty() bool

IsEmpty of the config

func (*Config) Keys added in v2.2.0

func (c *Config) Keys() []string

Keys get all config data

func (*Config) LoadData

func (c *Config) LoadData(dataSources ...any) (err error)

LoadData load data from map OR struct

The dataSources type allow:

  • map[string]any
  • map[string]string

func (*Config) LoadExists

func (c *Config) LoadExists(sourceFiles ...string) (err error)

LoadExists load and parse config files, but will ignore not exists file.

func (*Config) LoadExistsByFormat added in v2.0.26

func (c *Config) LoadExistsByFormat(format string, configFiles ...string) (err error)

LoadExistsByFormat load one or multi files by give format, will fire OnLoadData event

func (*Config) LoadFiles

func (c *Config) LoadFiles(sourceFiles ...string) (err error)

LoadFiles load and parse config files, will fire OnLoadData event

func (*Config) LoadFilesByFormat added in v2.0.26

func (c *Config) LoadFilesByFormat(format string, configFiles ...string) (err error)

LoadFilesByFormat load one or multi files by give format, will fire OnLoadData event

func (*Config) LoadFlags

func (c *Config) LoadFlags(keys []string) (err error)

LoadFlags parse command line arguments, based on provide keys.

Usage:

// 'debug' flag is bool type
c.LoadFlags([]string{"env", "debug:bool"})

func (*Config) LoadFromDir added in v2.1.8

func (c *Config) LoadFromDir(dirPath, format string, loFns ...LoadOptFn) (err error)

LoadFromDir Load custom format files from the given directory, the file name will be used as the key.

NOTE: will not be reloaded on call ReloadFiles(), if data loaded by the method.

Example:

// file: /somedir/task.json , will use filename 'task' as key
Config.LoadFromDir("/somedir", "json")

// after load, the data will be:
Config.data = map[string]any{"task": {file data}}

func (*Config) LoadOSEnv deprecated

func (c *Config) LoadOSEnv(keys []string, keyToLower bool)

LoadOSEnv load data from os ENV

Deprecated: please use Config.LoadOSEnvs()

func (*Config) LoadOSEnvs added in v2.1.7

func (c *Config) LoadOSEnvs(nameToKeyMap map[string]string)

LoadOSEnvs load data from os ENVs. format: {ENV_NAME: config_key}

func (*Config) LoadRemote

func (c *Config) LoadRemote(format, url string) (err error)

LoadRemote load config data from remote URL.

Usage:

c.LoadRemote(config.JSON, "http://abc.com/api-config.json")

func (*Config) LoadSMap added in v2.2.2

func (c *Config) LoadSMap(smp map[string]string)

LoadSMap to config

func (*Config) LoadSources

func (c *Config) LoadSources(format string, src []byte, more ...[]byte) (err error)

LoadSources load data from byte content.

Usage:

config.LoadSources(config.Yaml, []byte(`
  name: blog
  arr:
	key: val

`))

func (*Config) LoadStrings

func (c *Config) LoadStrings(format string, str string, more ...string) (err error)

LoadStrings load data from source string content.

func (*Config) LoadedFiles

func (c *Config) LoadedFiles() []string

LoadedFiles get loaded files name

func (*Config) LoadedUrls added in v2.1.7

func (c *Config) LoadedUrls() []string

LoadedUrls get loaded urls list

func (*Config) MapOnExists added in v2.1.0

func (c *Config) MapOnExists(key string, dst any) error

MapOnExists mapping data to the dst structure only on key exists.

  • Support ParseEnv on mapping
  • Support ParseDefault on mapping

func (*Config) MapStruct

func (c *Config) MapStruct(key string, dst any) error

MapStruct alias method of the 'Structure'

func (*Config) MustString added in v2.2.0

func (c *Config) MustString(key string) string

MustString get a string by key, will panic on empty or not exists

func (*Config) Name

func (c *Config) Name() string

Name get config name

func (*Config) Options

func (c *Config) Options() *Options

Options get

func (*Config) Readonly

func (c *Config) Readonly()

Readonly disable set data to config.

Usage:

config.LoadFiles(a, b, c)
config.Readonly()

func (*Config) ReloadFiles added in v2.1.7

func (c *Config) ReloadFiles() (err error)

ReloadFiles reload config data use loaded files. use on watching loaded files change

func (*Config) Set

func (c *Config) Set(key string, val any, setByPath ...bool) (err error)

Set a value by key string.

func (*Config) SetData added in v2.0.16

func (c *Config) SetData(data map[string]any)

SetData for override the Config.Data

func (*Config) SetDecoder deprecated

func (c *Config) SetDecoder(format string, decoder Decoder)

SetDecoder set decoder

Deprecated: please use driver instead

func (*Config) SetDecoders deprecated

func (c *Config) SetDecoders(decoders map[string]Decoder)

SetDecoders set decoders

Deprecated: please use driver instead

func (*Config) SetEncoder deprecated

func (c *Config) SetEncoder(format string, encoder Encoder)

SetEncoder set a encoder for the format

Deprecated: please use driver instead

func (*Config) SetEncoders deprecated

func (c *Config) SetEncoders(encoders map[string]Encoder)

SetEncoders set encoders

Deprecated: please use driver instead

func (*Config) String

func (c *Config) String(key string, defVal ...string) string

String get a string by key, if not found return default value

func (*Config) StringMap

func (c *Config) StringMap(key string) (mp map[string]string)

StringMap get config data as a map[string]string

func (*Config) Strings

func (c *Config) Strings(key string) (arr []string)

Strings get config data as a string slice/array

func (*Config) StringsBySplit added in v2.2.0

func (c *Config) StringsBySplit(key, sep string) (ss []string)

StringsBySplit get []string by split a string value.

func (*Config) Structure

func (c *Config) Structure(key string, dst any) (err error)

Structure get config data and binding to the dst structure.

  • Support ParseEnv on mapping
  • Support ParseDefault on mapping

Usage:

dbInfo := Db{}
config.Structure("db", &dbInfo)

func (*Config) Sub added in v2.2.4

func (c *Config) Sub(key string) map[string]any

Sub get sub config data by key

Note: will don't apply any options, like ParseEnv

func (*Config) SubDataMap added in v2.1.8

func (c *Config) SubDataMap(key string) maputil.Map

SubDataMap get sub config data as maputil.Map

TIP: will not enable parse Env and more

func (*Config) ToJSON

func (c *Config) ToJSON() string

ToJSON string, will ignore error

func (*Config) Uint

func (c *Config) Uint(key string, defVal ...uint) (value uint)

Uint get a int value, if not found return default value

func (*Config) With added in v2.0.22

func (c *Config) With(fn func(c *Config)) *Config

With apply some options

func (*Config) WithDriver added in v2.1.5

func (c *Config) WithDriver(drivers ...Driver) *Config

WithDriver set multi drivers at once.

func (*Config) WithOptions

func (c *Config) WithOptions(opts ...OptionFn) *Config

WithOptions apply some options

func (*Config) WriteTo

func (c *Config) WriteTo(out io.Writer) (n int64, err error)

WriteTo Write out config data representing the current state to a writer.

type Decoder

type Decoder func(blob []byte, v any) (err error)

Decoder for decode yml,json,toml format content

var JSONDecoder Decoder = func(data []byte, v any) (err error) {
	JSONDriver.ClearComments = JSONAllowComments
	return JSONDriver.Decode(data, v)
}

JSONDecoder for json decode

type Driver

type Driver interface {
	Name() string
	Aliases() []string // alias format names, use for resolve format name
	GetDecoder() Decoder
	GetEncoder() Encoder
}

Driver interface. TODO refactor: rename GetDecoder() to Decode(), rename GetEncoder() to Encode()

type DriverV2 added in v2.2.2

type DriverV2 interface {
	Name() string      // driver name, also is format name.
	Aliases() []string // alias format names, use for resolve format name
	Decode(blob []byte, v any) (err error)
	Encode(v any) (out []byte, err error)
}

DriverV2 interface.

type Encoder

type Encoder func(v any) (out []byte, err error)

Encoder for decode yml,json,toml format content

var JSONEncoder Encoder = func(v any) (out []byte, err error) {
	JSONDriver.MarshalIndent = JSONMarshalIndent
	return JSONDriver.Encode(v)
}

JSONEncoder for json encode

type HookFunc added in v2.1.0

type HookFunc func(event string, c *Config)

HookFunc on config data changed.

type LoadOptFn added in v2.2.5

type LoadOptFn func(lo *LoadOptions)

LoadOptFn type func

type LoadOptions added in v2.2.5

type LoadOptions struct {
	// DataKey use for load config from dir.
	// see https://github.com/gookit/config/issues/173
	DataKey string
}

LoadOptions for load config from dir.

type OptionFn added in v2.2.2

type OptionFn func(*Options)

OptionFn option func

type Options

type Options struct {
	// ParseEnv parse env in string value and default value. like: "${EnvName}" "${EnvName|default}"
	ParseEnv bool
	// ParseTime parses a duration string to time.Duration
	// eg: 10s, 2m
	ParseTime bool
	// Readonly config is readonly
	Readonly bool
	// ParseDefault tag on binding data to struct. tag: default
	ParseDefault bool
	// EnableCache enable config data cache
	EnableCache bool
	// ParseKey parse key path, allow find value by key path. eg: 'key.sub' will find `map[key]sub`
	ParseKey bool
	// TagName tag name for binding data to struct
	//
	// Deprecated: please set tag name by DecoderConfig, or use SetTagName()
	TagName string
	// Delimiter the delimiter char for split key path, if `FindByPath=true`. default is '.'
	Delimiter byte
	// DumpFormat default write format
	DumpFormat string
	// ReadFormat default input format
	ReadFormat string
	// DecoderConfig setting for binding data to struct. such as: TagName
	DecoderConfig *mapstructure.DecoderConfig
	// HookFunc on data changed. you can do something...
	HookFunc HookFunc
	// MergeOptions settings for merge two data
	MergeOptions []func(*mergo.Config)
}

Options config options

func GetOptions

func GetOptions() *Options

GetOptions get options

func (*Options) SetTagName added in v2.2.5

func (o *Options) SetTagName(tagName string)

SetTagName for mapping data to struct

type StdDriver added in v2.1.1

type StdDriver struct {
	// contains filtered or unexported fields
}

StdDriver struct

func NewDriver added in v2.1.1

func NewDriver(name string, dec Decoder, enc Encoder) *StdDriver

NewDriver new std driver instance.

func (*StdDriver) Aliases added in v2.2.2

func (d *StdDriver) Aliases() []string

Aliases format name of driver

func (*StdDriver) Decode added in v2.1.1

func (d *StdDriver) Decode(blob []byte, v any) (err error)

Decode of driver

func (*StdDriver) Encode added in v2.1.1

func (d *StdDriver) Encode(v any) ([]byte, error)

Encode of driver

func (*StdDriver) GetDecoder added in v2.1.1

func (d *StdDriver) GetDecoder() Decoder

GetDecoder of driver

func (*StdDriver) GetEncoder added in v2.1.1

func (d *StdDriver) GetEncoder() Encoder

GetEncoder of driver

func (*StdDriver) Name added in v2.1.1

func (d *StdDriver) Name() string

Name of driver

func (*StdDriver) WithAlias added in v2.2.2

func (d *StdDriver) WithAlias(alias string) *StdDriver

WithAlias add alias for driver

func (*StdDriver) WithAliases added in v2.2.2

func (d *StdDriver) WithAliases(aliases ...string) *StdDriver

WithAliases set aliases for driver

Directories

Path Synopsis
These are some sample code for YAML,TOML,JSON,INI,HCL
These are some sample code for YAML,TOML,JSON,INI,HCL
Package hcl is driver use HCL format content as config source
Package hcl is driver use HCL format content as config source
Package hclv2 is driver use HCL format content as config source
Package hclv2 is driver use HCL format content as config source
Package ini is driver use INI format content as config source
Package ini is driver use INI format content as config source
Package json use the https://github.com/json-iterator/go for parse json
Package json use the https://github.com/json-iterator/go for parse json
Package json5 support for parse and load json5
Package json5 support for parse and load json5
Package other is an example of a custom driver
Package other is an example of a custom driver
Package properties is a driver use Java properties format content as config source
Package properties is a driver use Java properties format content as config source
Package toml is driver use TOML format content as config source.
Package toml is driver use TOML format content as config source.
Package yaml is a driver use YAML format content as config source
Package yaml is a driver use YAML format content as config source
Package yamlv3 is a driver use YAML format content as config source
Package yamlv3 is a driver use YAML format content as config source

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL