config

package module
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: Jul 20, 2018 License: MIT Imports: 12 Imported by: 23

README

config

GoDoc

golang application config manage tool library.

  • support multi format: JSON(default), INI, YAML, TOML, HCL
  • 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 ...

中文说明

Godoc

Usage

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

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

map1:
    key: val2
    key2: val20

arr1:
    - val1
    - val21
package main

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

// go run ./examples/yaml.go
func main() {
	config.SetOptions(&config.Options{
		ParseEnv: true,
	})
	
	// config.SetDecoder(config.Yaml, yaml.Decoder)
	config.DecoderEncoder(config.Yaml, yaml.Decoder, yaml.Encoder)

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

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

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

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

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

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

	val0, ok = config.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", config.DefString("envKey", ""))
	fmt.Printf("get env 'envKey1' val: %s\n", config.DefString("envKey1", ""))

	// set value
	config.Set("name", "new name")
	name, ok = config.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.Yaml)
	// if err != nil {
	// 	panic(err)
	// }
	// fmt.Printf("export config:\n%s", buf.String())
}
  • output:
get config example:
get string
 - ok: true, val: app2
get array
 - ok: true, val: []string{"val1", "val21"}
get sub-value by path 'arr.index'
 - ok: true, val: "val1"
get map
 - ok: true, val: map[string]string{"key":"val2", "key2":"val20"}
get sub-value by path 'map.key'
 - ok: true, val: "val2"
get env 'envKey' val: /bin/zsh
get env 'envKey1' val: defValue
set string
- ok: true, val: new name

Useful packages

Yaml parse
Toml parse
Ini parse
Data merge
Ini config use

License

MIT

Documentation

Overview

golang application config manage 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
SetOptions(&Options{
	ParseEnv: true,
})

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

supported config format

View Source
const Version = "1.0.3"

package version

Variables

View Source
var JsonDriver = &jsonDriver{Json}

JsonDriver

Functions

func AddDriver added in v1.0.3

func AddDriver(format string, 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

func ClearAll added in v1.0.3

func ClearAll()

ClearAll

func ClearData added in v1.0.3

func ClearData()

ClearData

func Data

func Data() map[string]interface{}

Data return all config data

func DecoderEncoder added in v1.0.3

func DecoderEncoder(format string, decoder Decoder, encoder Encoder)

DecoderEncoder set a decoder and encoder for a format.

func DefBool

func DefBool(key string, def bool) bool

DefBool get a bool 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

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

func Get

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

Get

func Int added in v1.0.5

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

Int

func Int64 added in v1.0.5

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

Int64

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

func LoadExists added in v1.0.3

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

LoadExists

func LoadFiles

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

LoadFiles

func LoadSources

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

LoadSources

func LoadStrings added in v1.0.3

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

LoadStrings

func Set

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

Set

func SetDecoder

func SetDecoder(format string, decoder Decoder)

SetDecoder add/set a format decoder

func SetDecoders added in v1.0.2

func SetDecoders(decoders map[string]Decoder)

SetDecoders

func SetEncoder added in v1.0.2

func SetEncoder(format string, encoder Encoder)

SetEncoder

func SetEncoders added in v1.0.2

func SetEncoders(encoders map[string]Encoder)

SetEncoders

func SetOptions

func SetOptions(opts *Options)

SetOptions

func String added in v1.0.5

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

String

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

func WriteTo added in v1.0.2

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

WriteTo

Types

type Config

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

Config

func Default added in v1.0.5

func Default() *Config

Default get the default instance

func New

func New(name string) *Config

New

func (*Config) AddDriver added in v1.0.3

func (c *Config) AddDriver(format string, 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

func (*Config) ClearCaches

func (c *Config) ClearCaches()

ClearCaches

func (*Config) ClearData

func (c *Config) ClearData()

ClearData

func (*Config) Data

func (c *Config) Data() map[string]interface{}

Data get all config data

func (*Config) DecoderEncoder added in v1.0.3

func (c *Config) DecoderEncoder(format string, decoder Decoder, encoder Encoder)

DecoderEncoder set a decoder and encoder for a format.

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

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

func (*Config) HasEncoder added in v1.0.2

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

HasEncoder

func (*Config) Int added in v1.0.5

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

Int

func (*Config) Int64 added in v1.0.5

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

Int64

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 'GetStructure'

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

MustInt 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) Readonly

func (c *Config) Readonly(readonly bool)

Readonly

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

func (*Config) SetDecoders added in v1.0.2

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

SetDecoders

func (*Config) SetEncoder added in v1.0.2

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

SetEncoder

func (*Config) SetEncoders added in v1.0.2

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

SetEncoders

func (*Config) SetOptions

func (c *Config) SetOptions(opts *Options)

SetOptions

func (*Config) String added in v1.0.5

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

String

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)

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

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

func (*Config) ToJson added in v1.0.5

func (c *Config) ToJson() string

ToJson string

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(blob []byte, v interface{}) (err error) {
	return json.Unmarshal(blob, v)
}

JsonDecoder

type Driver added in v1.0.3

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

Driver

type Encoder

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

Encoder for decode yml,json,toml format content

var JsonEncoder Encoder = func(v interface{}) (out []byte, err error) {
	return json.Marshal(v)
}

JsonEncoder

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

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
This is driver use HCL format content as config source about HCL, please see https://github.com/hashicorp/hcl
This is driver use HCL format content as config source about HCL, please see https://github.com/hashicorp/hcl
This is driver use INI format content as config source about ini parse, please see https://github.com/gookit/ini/parser
This is driver use INI format content as config source about ini parse, please see https://github.com/gookit/ini/parser
use the https://github.com/json-iterator/go for parse json
use the https://github.com/json-iterator/go for parse json
This is driver use TOML format content as config source Usage please see example:
This is driver use TOML format content as config source Usage please see example:
Here use YAML format content as config source Usage please see example:
Here 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