config

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Jul 15, 2018 License: MIT Imports: 11 Imported by: 0

README

config

GoDoc

golang application config manage implement.

  • generic api Get GetInt GetString GetBool GetStringArr GetStringMap ...
  • support multi format: json(default), yaml, toml
  • 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

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.SetDriver(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.GetString("name")
	fmt.Printf("- get string\n ok: %v, val: %v\n", ok, name)

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

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

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

	val0, ok = config.GetString("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", ""))

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

Useful packages

ini config use
yaml
toml
data merge

License

MIT

Documentation

Overview

golang application config manage implement. support yaml,toml,json format.

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

https://github.com/gookit/config

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

name: app2
debug: false
baseKey: value2

map1:
    key: val2
    key2: val20

arr1:
    - val1
    - val21

usage please see examples:

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

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

fmt.Printf("export config:\n%s", buf.String())
Output:

arr1:
	- val1
	- val21
baseKey: value2
debug: false
... ...
Example (UseToml)
SetOptions(&Options{
	ParseEnv: true,
})
SetDriver(Toml, toml.Decoder, toml.Encoder)

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

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

// load more files
err = LoadFiles("testdata/toml_other.toml")
// can also
// LoadFiles("testdata/toml_base.toml", "testdata/toml_other.toml")
if err != nil {
	panic(err)
}

// load from string
LoadSources(Toml, []byte(tomlStr))

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

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

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

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

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

val0, ok = GetString("map1.name")
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", ""))
Output:

get config example:
- get string
ok: true, val: app2
- get array
ok: true, val: []string{"alpha", "omega"}
- get sub-value by path 'arr.index'
ok: true, val: alpha
- get map
ok: true, val: map[string]string{"name":"Tom Preston-Werner", "org":"GitHub"}
- get sub-value by path 'map.key'
ok: true, val: Tom Preston-Werner
get env 'envKey' val: /bin/zsh
get env 'envKey1' val: defValue
Example (UseYaml)
// add yaml decoder
SetDecoder(Yaml, yaml.Decoder)
err := LoadFiles("testdata/yml_other.yml")
if err != nil {
	panic(err)
}

// load from string
LoadSources(Yaml, []byte(yamlStr))

fmt.Print("get config example:\n")

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

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

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

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

val0, ok = GetString("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", ""))
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

Index

Examples

Constants

View Source
const (
	Json = "json"
	Yml  = "yml"
	Yaml = "yaml"
	Toml = "toml"
)

supported config format

View Source
const Version = "1.0.1"

package version

Variables

This section is empty.

Functions

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 DefInt

func DefInt(key string, def int) int

DefInt get a int value, if not found return 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

func Get

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

Get

func GetBool

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

GetBool

func GetInt

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

GetInt

func GetString

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

GetString

func GetStringArr

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

GetStringArr

func GetStringMap

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

GetStringMap get config data as a map[string]string

func LoadData

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

LoadData

func LoadFiles

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

LoadFiles

func LoadSources

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

LoadSources

func Set

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

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

SetDriver set a decoder and encoder for a format.

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

func New(name string) *Config

New

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

func (c *Config) DefBool(key string, def bool) bool

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

Example
val, ok := GetBool("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) 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) GetBool

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

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

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

GetInt

func (*Config) GetString

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

GetString

func (*Config) GetStringArr

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

GetStringArr get config data as a slice/array

func (*Config) GetStringMap

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

GetStringMap get config data as a map[string]string

func (*Config) GetStructure

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

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

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

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) 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, sourceCodes ...[]byte) (err error)

LoadSources load data from byte content. usage:

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

`))

func (*Config) MapStructure

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

MapStructure alias method of the 'GetStructure'

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{}) (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) SetDriver added in v1.0.2

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

SetDriver set a decoder and encoder for a format.

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

var JsonDecoder Decoder = func(blob []byte, v interface{}) (err error) {
	return json.Unmarshal(blob, v)
}

JsonDecoder

type Encoder

type Encoder func(v interface{}) (out []byte, err error)
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
	// default write format
	DumpFormat string
	// default input format
	ReadFormat string
}

Options config options

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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