README

config

GoDoc Build Status Coverage Status Go Report Card

Golang application config manage tool library.

中文说明

  • Support multi format: JSON(default), INI, YAML, TOML, HCL
    • JSON content support comments. will auto clear comments
  • Support multi-file and multi-data loading
  • Support for loading configuration data from remote URLs
  • Support for setting configuration data from command line arguments(flags)
  • Support data overlay and merge, automatically load by key when loading multiple copies of data
  • Support get sub value by path, like map.key arr.2
  • Support parse ENV name. like envKey: ${SHELL} -> envKey: /bin/zsh
  • Generic api Get Int 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

GoDoc

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"
    "github.com/gookit/config/yaml"
)

// go run ./examples/yaml.go
func main() {
	config.WithOptions(config.ParseEnv)
	
	// add driver for support yaml content
	config.AddDriver(yaml.Driver)
	// config.SetDecoder(config.Yaml, yaml.Decoder)

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

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

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

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

API Methods Refer

Load Config
  • LoadData(dataSource ...interface{}) (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)
  • LoadRemote(format, url string) (err error)
  • LoadSources(format string, src []byte, more ...[]byte) (err error)
  • LoadStrings(format string, str string, more ...string) (err error)
Getting Values

DefXXX get value with default value

  • Bool(key string) (value bool, ok bool)
  • DefBool(key string, defVal ...bool) bool
  • Int(key string) (value int, ok bool)
  • DefInt(key string, defVal ...int) int
  • Int64(key string) (value int64, ok bool)
  • DefInt64(key string, defVal ...int64)
  • Ints(key string) (arr []int, ok bool)
  • IntMap(key string) (mp map[string]int, ok bool)
  • Float(key string) (value float64, ok bool)
  • DefFloat(key string, defVal ...float64) float64
  • String(key string) (value string, ok bool)
  • DefString(key string, defVal ...string) string
  • Strings(key string) (arr []string, ok bool)
  • StringMap(key string) (mp map[string]string, ok bool)
  • Get(key string, findByPath ...bool) (value interface{}, ok bool)
Setting Values
  • Set(key string, val interface{}, setByPath ...bool) (err error)
Useful Methods
  • AddDriver(driver Driver)
  • Data() map[string]interface{}
  • DumpTo(out io.Writer, format string) (n int64, err error)

Run Tests

go test -cover
// contains all sub-folder
go test -cover ./...
Ini Config Use

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
    Output:
    
    
    Example (ExportConfig)
    Output:
    
    {"age":34,"name":"app"}
    

    Index

    Examples

    Constants

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

      There are supported config format

      View Source
      const Version = "1.1.0"

        Version is package version

        Variables

        View Source
        var JSONDriver = &jsonDriver{name: JSON}

          JSONDriver instance fot json

          Functions

          func AddDriver

          func AddDriver(driver Driver)

            AddDriver set a decoder and encoder driver for a format.

            func Bool

            func Bool(key string) (bool, bool)

              Bool get a bool by key

              func ClearAll

              func ClearAll()

                ClearAll data and caches

                func Data

                func Data() map[string]interface{}

                  Data return all config data

                  func DefBool

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

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

                    func DefFloat

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

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

                      func DefInt

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

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

                        func DefInt64

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

                          DefInt64 get a int64 with a default value

                          func DefString

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

                            DefString get a string value, if not found return default value

                            func DumpTo

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

                              DumpTo a writer and use format

                              func EnableCache

                              func EnableCache(opts *Options)

                                EnableCache set readonly

                                func Float

                                func Float(key string) (float64, bool)

                                  Float get a bool by key

                                  func Get

                                  func Get(key string, findByPath ...bool) (interface{}, bool)

                                    Get get a value by key

                                    func Int

                                    func Int(key string) (int, bool)

                                      Int get a int by key

                                      func Int64

                                      func Int64(key string) (int64, bool)

                                        Int64 get a int64 by key

                                        func IntMap

                                        func IntMap(key string) (map[string]int, bool)

                                          IntMap get config data as a map[string]int

                                          func Ints

                                          func Ints(key string) ([]int, bool)

                                            Ints get config data as a int slice/array

                                            func LoadData

                                            func LoadData(dataSource ...interface{}) error

                                              LoadData load one or multi data

                                              func LoadExists

                                              func LoadExists(sourceFiles ...string) error

                                                LoadExists load one or multi files, will ignore not exist

                                                func LoadFiles

                                                func LoadFiles(sourceFiles ...string) error

                                                  LoadFiles load one or multi files

                                                  func LoadFlags

                                                  func LoadFlags(keys []string) error

                                                    LoadFlags load data from cli flags

                                                    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 ParseEnv

                                                        func ParseEnv(opts *Options)

                                                          ParseEnv set parse env

                                                          func Readonly

                                                          func Readonly(opts *Options)

                                                            Readonly set readonly

                                                            func Set

                                                            func Set(key string, val interface{}, setByPath ...bool) error

                                                              Set val by key

                                                              func SetDecoder

                                                              func SetDecoder(format string, decoder Decoder)

                                                                SetDecoder add/set a format decoder

                                                                func SetEncoder

                                                                func SetEncoder(format string, encoder Encoder)

                                                                  SetEncoder set a encoder for the format

                                                                  func String

                                                                  func String(key string) (string, bool)

                                                                    String get a string by key

                                                                    func StringMap

                                                                    func StringMap(key string) (map[string]string, bool)

                                                                      StringMap get config data as a map[string]string

                                                                      func Strings

                                                                      func Strings(key string) ([]string, bool)

                                                                        Strings get strings by key

                                                                        func StripJSONComments

                                                                        func StripJSONComments(src string) string

                                                                          StripJSONComments for a JSON string

                                                                          func WithOptions

                                                                          func WithOptions(opts ...func(*Options))

                                                                            WithOptions with options

                                                                            func WriteTo

                                                                            func WriteTo(out io.Writer) (n int64, err 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) *Config

                                                                                    New config instance

                                                                                    func NewEmpty

                                                                                    func NewEmpty(name string) *Config

                                                                                      NewEmpty config instance

                                                                                      func NewWithOptions

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

                                                                                        NewWithOptions config instance

                                                                                        func (*Config) AddDriver

                                                                                        func (c *Config) AddDriver(driver Driver)

                                                                                          AddDriver set a decoder and encoder driver for a format.

                                                                                          func (*Config) Bool

                                                                                          func (c *Config) Bool(key string) (value bool, ok 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]interface{}

                                                                                                    Data get all config data

                                                                                                    func (*Config) DefBool

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

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

                                                                                                      Example
                                                                                                      Output:
                                                                                                      
                                                                                                      get 'debug', ok: true, val: true
                                                                                                      get 'debug' with default, val: true
                                                                                                      

                                                                                                      func (*Config) DefFloat

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

                                                                                                        DefFloat get a float value, if not found return default value

                                                                                                        func (*Config) DefInt

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

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

                                                                                                          func (*Config) DefInt64

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

                                                                                                            DefInt64 get a int64 with a default value

                                                                                                            func (*Config) DefString

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

                                                                                                              DefString get a string value, if not found return default value

                                                                                                              func (*Config) DelDriver

                                                                                                              func (c *Config) DelDriver(format string)

                                                                                                                DelDriver delete driver of the format

                                                                                                                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) Error

                                                                                                                  func (c *Config) Error() error

                                                                                                                    Error get last error

                                                                                                                    func (*Config) Float

                                                                                                                    func (c *Config) Float(key string) (value float64, ok bool)

                                                                                                                      Float get a float64 by key

                                                                                                                      func (*Config) Get

                                                                                                                      func (c *Config) Get(key string, findByPath ...bool) (value interface{}, ok bool)

                                                                                                                        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 (*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) (value int, ok bool)

                                                                                                                              Int get a int by key

                                                                                                                              func (*Config) Int64

                                                                                                                              func (c *Config) Int64(key string) (value int64, ok bool)

                                                                                                                                Int64 get a int64 by key

                                                                                                                                func (*Config) IntMap

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

                                                                                                                                  IntMap get config data as a map[string]int

                                                                                                                                  func (*Config) Ints

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

                                                                                                                                    Ints get config data as a int slice/array

                                                                                                                                    func (*Config) IsEmpty

                                                                                                                                    func (c *Config) IsEmpty() bool

                                                                                                                                      IsEmpty of the config

                                                                                                                                      func (*Config) LoadData

                                                                                                                                      func (c *Config) LoadData(dataSources ...interface{}) (err error)

                                                                                                                                        LoadData load data from map OR struct

                                                                                                                                        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) LoadFiles

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

                                                                                                                                            LoadFiles load and parse config files

                                                                                                                                            func (*Config) LoadFlags

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

                                                                                                                                              LoadFlags parse command line arguments, based on provide keys. Usage:

                                                                                                                                              c.LoadFlags([]string{"env", "debug"})
                                                                                                                                              

                                                                                                                                              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) LoadSources

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

                                                                                                                                                  LoadSources load data from byte content. Usage:

                                                                                                                                                  config.LoadSources(config.Yml, []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) MapStruct

                                                                                                                                                      func (c *Config) MapStruct(key string, v interface{}) (err error)

                                                                                                                                                        MapStruct alias method of the 'Structure'

                                                                                                                                                        func (*Config) MapStructure

                                                                                                                                                        func (c *Config) MapStructure(key string, v interface{}) (err error)

                                                                                                                                                          MapStructure alias method of the 'Structure'

                                                                                                                                                          func (*Config) MustBool

                                                                                                                                                          func (c *Config) MustBool(key string) bool

                                                                                                                                                            MustBool get a string value, if not found return false

                                                                                                                                                            func (*Config) MustInt

                                                                                                                                                            func (c *Config) MustInt(key string) int

                                                                                                                                                              MustInt get a int value, if not found return 0

                                                                                                                                                              func (*Config) MustInt64

                                                                                                                                                              func (c *Config) MustInt64(key string) int64

                                                                                                                                                                MustInt64 get a int value, if not found return 0

                                                                                                                                                                func (*Config) MustString

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

                                                                                                                                                                  MustString get a string value, if not found return empty string

                                                                                                                                                                  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) Set

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

                                                                                                                                                                          Set a value by key string.

                                                                                                                                                                          func (*Config) SetDecoder

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

                                                                                                                                                                            SetDecoder set decoder

                                                                                                                                                                            func (*Config) SetDecoders

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

                                                                                                                                                                              SetDecoders set decoders

                                                                                                                                                                              func (*Config) SetEncoder

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

                                                                                                                                                                                SetEncoder set a encoder for the format

                                                                                                                                                                                func (*Config) SetEncoders

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

                                                                                                                                                                                  SetEncoders set encoders

                                                                                                                                                                                  func (*Config) String

                                                                                                                                                                                  func (c *Config) String(key string) (value string, ok bool)

                                                                                                                                                                                    String get a string by key

                                                                                                                                                                                    func (*Config) StringMap

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

                                                                                                                                                                                      StringMap get config data as a map[string]string

                                                                                                                                                                                      func (*Config) Strings

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

                                                                                                                                                                                        Strings get config data as a string slice/array

                                                                                                                                                                                        func (*Config) Structure

                                                                                                                                                                                        func (c *Config) Structure(key string, v interface{}) (err error)

                                                                                                                                                                                          Structure get config data and map to a structure. usage:

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

                                                                                                                                                                                          func (*Config) ToJSON

                                                                                                                                                                                          func (c *Config) ToJSON() string

                                                                                                                                                                                            ToJSON string

                                                                                                                                                                                            func (*Config) WithOptions

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

                                                                                                                                                                                              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 interface{}) (err error)

                                                                                                                                                                                                  Decoder for decode yml,json,toml format content

                                                                                                                                                                                                  var JSONDecoder Decoder = func(data []byte, v interface{}) (err error) {
                                                                                                                                                                                                  	str := StripJSONComments(string(data))
                                                                                                                                                                                                  	return json.Unmarshal([]byte(str), v)
                                                                                                                                                                                                  }

                                                                                                                                                                                                    JSONDecoder for json decode

                                                                                                                                                                                                    type Driver

                                                                                                                                                                                                    type Driver interface {
                                                                                                                                                                                                    	Name() string
                                                                                                                                                                                                    	GetDecoder() Decoder
                                                                                                                                                                                                    	GetEncoder() Encoder
                                                                                                                                                                                                    }

                                                                                                                                                                                                      Driver interface

                                                                                                                                                                                                      type Encoder

                                                                                                                                                                                                      type Encoder func(v interface{}) (out []byte, err error)

                                                                                                                                                                                                        Encoder for decode yml,json,toml format content

                                                                                                                                                                                                        var JSONEncoder Encoder = json.Marshal

                                                                                                                                                                                                          JSONEncoder for json encode

                                                                                                                                                                                                          type Options

                                                                                                                                                                                                          type Options struct {
                                                                                                                                                                                                          	// parse env value. like: "${EnvName}" "${EnvName|default}"
                                                                                                                                                                                                          	ParseEnv bool
                                                                                                                                                                                                          	// config is readonly
                                                                                                                                                                                                          	Readonly bool
                                                                                                                                                                                                          	// enable config data cache
                                                                                                                                                                                                          	EnableCache bool
                                                                                                                                                                                                          	// default write format
                                                                                                                                                                                                          	DumpFormat string
                                                                                                                                                                                                          	// default input format
                                                                                                                                                                                                          	ReadFormat string
                                                                                                                                                                                                          }

                                                                                                                                                                                                            Options config options

                                                                                                                                                                                                            func GetOptions

                                                                                                                                                                                                            func GetOptions() *Options

                                                                                                                                                                                                              GetOptions get options

                                                                                                                                                                                                              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 about HCL, please see https://github.com/hashicorp/hcl
                                                                                                                                                                                                              Package hcl is driver use HCL format content as config source about HCL, please see https://github.com/hashicorp/hcl
                                                                                                                                                                                                              Package ini is driver use INI format content as config source about ini parse, please see https://github.com/gookit/ini/parser
                                                                                                                                                                                                              Package ini is driver use INI format content as config source about ini parse, please see https://github.com/gookit/ini/parser
                                                                                                                                                                                                              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 toml is driver use TOML format content as config source Usage please see example:
                                                                                                                                                                                                              Package toml is driver use TOML format content as config source Usage please see example:
                                                                                                                                                                                                              Package yaml is a driver use YAML format content as config source Usage please see example:
                                                                                                                                                                                                              Package yaml is a driver use YAML format content as config source Usage please see example: