config

package module
v1.0.10 Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2018 License: MIT Imports: 13 Imported by: 22

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/data load
  • support data override merge
  • 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(coverage > 90%)

中文说明

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, age) // 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)
  • LoadExists(sourceFiles ...string) (err error)
  • LoadFiles(sourceFiles ...string) (err error)
  • LoadSources(format string, src []byte, more ...[]byte) (err error)
  • LoadStrings(format string, str string, more ...string) (err error)
Getting Values
  • Bool(key string) (value bool, ok bool)
  • Int(key string) (value int, ok bool)
  • Int64(key string) (value int64, ok bool)
  • Ints(key string) (arr []int, ok bool)
  • IntMap(key string) (mp map[string]int, ok bool)
  • Float(key string) (value float64, ok bool)
  • String(key string) (value string, ok bool)
  • 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)

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
WithOptions(ParseEnv)

// add Decoder and Encoder
// use yaml github.com/gookit/config/yaml
// AddDriver(Yaml, yaml.Driver)
// use toml github.com/gookit/config/toml
// AddDriver(Toml, toml.Driver)
// use toml github.com/gookit/config/hcl
// AddDriver(Hcl, hcl.Driver)
// Or
// config.DecoderEncoder(config.JSON, yaml.Decoder, yaml.Encoder)

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
LoadSources(JSON, []byte(jsonStr))

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

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

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

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

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

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

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

// set value
Set("name", "new name")
name, ok = String("name")
fmt.Printf("- set string\n ok: %v, val: %v\n", ok, 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
//  ok: true, val: app
// - get array
//  ok: true, val: []string{"val", "val1", "val2"}
// - get sub-value by path 'arr.index'
//  ok: true, val: "val"
// - get map
//  ok: true, val: map[string]string{"key":"val", "key1":"val1", "key2":"val2"}
// - get sub-value by path 'map.key'
//  ok: true, val: "val"
// get env 'envKey' val: /bin/zsh
// get env 'envKey1' val: defValue
// - set string
//  ok: true, val: new name
Output:

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

ClearAll()
// load from string
LoadStrings(JSON, `{
"name": "app",
"age": 34
}`)

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

There are supported config format

View Source
const Version = "1.0.6"

Version is package version

Variables

View Source
var JSONDriver = &jsonDriver{JSON}

JSONDriver instance fot json

Functions

func AddDriver added in v1.0.3

func AddDriver(driver Driver)

AddDriver set a decoder and encoder driver for a format.

func Bool added in v1.0.5

func Bool(key string) (value bool, ok bool)

Bool get a bool by key

func ClearAll added in v1.0.3

func ClearAll()

ClearAll data and caches

func ClearJSONComments added in v1.0.9

func ClearJSONComments(str string) string

ClearJSONComments for a JSON string

func Data

func Data() map[string]interface{}

Data return all config data

func DefBool

func DefBool(key string, def bool) bool

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

func DefFloat added in v1.0.10

func DefFloat(key string, def float64) float64

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

func DefInt

func DefInt(key string, def int) int

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

func DefInt64 added in v1.0.3

func DefInt64(key string, def int64) int64

DefInt64 get a int64 with a default value

func DefString

func DefString(key string, def string) string

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

func DumpTo added in v1.0.2

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

DumpTo a writer and use format

func EnableCache added in v1.0.6

func EnableCache(opts *Options)

EnableCache set readonly

func Float added in v1.0.10

func Float(key string) (value float64, ok bool)

Float get a bool by key

func Get

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

Get get a value by key

func Int added in v1.0.5

func Int(key string) (value int, ok bool)

Int get a int by key

func Int64 added in v1.0.5

func Int64(key string) (value int64, ok bool)

Int64 get a int64 by key

func IntMap added in v1.0.5

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

IntMap get config data as a map[string]int

func Ints added in v1.0.5

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

Ints get config data as a int slice/array

func LoadData

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

LoadData load one or multi data

func LoadExists added in v1.0.3

func LoadExists(sourceFiles ...string) (err error)

LoadExists load one or multi files, will ignore not exist

func LoadFiles

func LoadFiles(sourceFiles ...string) (err error)

LoadFiles load one or multi files

func LoadSources

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

LoadSources load one or multi byte data

func LoadStrings added in v1.0.3

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

LoadStrings load one or multi string

func ParseEnv added in v1.0.6

func ParseEnv(opts *Options)

ParseEnv set parse env

func Readonly added in v1.0.6

func Readonly(opts *Options)

Readonly set readonly

func Set

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

Set val by key

func SetDecoder

func SetDecoder(format string, decoder Decoder)

SetDecoder add/set a format decoder

func SetEncoder added in v1.0.2

func SetEncoder(format string, encoder Encoder)

SetEncoder set a encoder for the format

func String added in v1.0.5

func String(key string) (value string, ok bool)

String get a string by key

func StringMap added in v1.0.5

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

StringMap get config data as a map[string]string

func Strings added in v1.0.5

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

Strings get strings by key

func WithOptions added in v1.0.6

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

WithOptions with options

func WriteTo added in v1.0.2

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 added in v1.0.5

func Default() *Config

Default get the default instance

func New

func New(name string) *Config

New config instance

func NewEmpty added in v1.0.6

func NewEmpty(name string) *Config

NewEmpty config instance

func NewWithOptions added in v1.0.6

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

NewWithOptions config instance

func (*Config) AddDriver added in v1.0.3

func (c *Config) AddDriver(driver Driver)

AddDriver set a decoder and encoder driver for a format.

func (*Config) Bool added in v1.0.5

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, def bool) bool

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

Example
// load from string
LoadSources(JSON, []byte(jsonStr))

val, ok := Bool("debug")
fmt.Printf("get 'debug', ok: %v, val: %v\n", ok, val)
val1 := DefBool("debug", false)
fmt.Printf("get 'debug' with default, val: %v\n", val1)
Output:

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

func (*Config) DefFloat added in v1.0.10

func (c *Config) DefFloat(key string, def float64) float64

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

func (*Config) DefInt

func (c *Config) DefInt(key string, def int) int

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

func (*Config) DefInt64 added in v1.0.3

func (c *Config) DefInt64(key string, def int64) int64

DefInt64 get a int64 with a default value

func (*Config) DefString

func (c *Config) DefString(key string, def string) string

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

func (*Config) DelDriver added in v1.0.6

func (c *Config) DelDriver(format string)

DelDriver delete driver of the format

func (*Config) DumpTo added in v1.0.2

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) Float added in v1.0.10

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 added in v1.0.2

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

HasEncoder has encoder

func (*Config) Int added in v1.0.5

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

Int get a int by key

func (*Config) Int64 added in v1.0.5

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

Int64 get a int64 by key

func (*Config) IntMap added in v1.0.5

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

IntMap get config data as a map[string]int

func (*Config) Ints added in v1.0.5

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

Ints get config data as a int slice/array

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) 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 added in v1.0.3

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

LoadStrings load data from source string content.

func (*Config) MapStructure

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

MapStructure alias method of the 'Structure'

func (*Config) MustBool added in v1.0.5

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

MustBool get a string value, if not found return false

func (*Config) MustInt added in v1.0.5

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

MustInt get a int value, if not found return 0

func (*Config) MustInt64 added in v1.0.5

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

MustInt64 get a int value, if not found return 0

func (*Config) MustString added in v1.0.5

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 added in v1.0.6

func (c *Config) Options() *Options

Options get

func (*Config) Set added in v1.0.1

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 added in v1.0.2

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

SetDecoders set decoders

func (*Config) SetEncoder added in v1.0.2

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

SetEncoder set a encoder for the format

func (*Config) SetEncoders added in v1.0.2

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

SetEncoders set encoders

func (*Config) String added in v1.0.5

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

String get a string by key

func (*Config) StringMap added in v1.0.5

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

StringMap get config data as a map[string]string

func (*Config) Strings added in v1.0.5

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

Strings get config data as a string slice/array

func (*Config) Structure added in v1.0.5

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 added in v1.0.7

func (c *Config) ToJSON() string

ToJSON string

func (*Config) WithOptions added in v1.0.6

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

WithOptions apply some options

func (*Config) WriteTo added in v1.0.2

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 := ClearJSONComments(string(data))
	return json.Unmarshal([]byte(str), v)
}

JSONDecoder for json decode

type Driver added in v1.0.3

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 added in v1.0.6

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:

Jump to

Keyboard shortcuts

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