config

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2018 License: MIT Imports: 11 Imported by: 23

README

config

GoDoc

golang application config manage implement.

  • support multi format: JSON(default), 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 GetInt GetString GetBool GetStringArr GetStringMap ...

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

	// set value
	config.Set("name", "new name")
	name, ok = config.GetString("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
Toml
Data merge
Ini config use

License

MIT

Documentation

Overview

golang application config manage implement. support YAML,TOML,JSON,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 := 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", ""))

// set value
Set("name", "new name")
name, ok = GetString("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 (
	Json = "json"
	Hcl  = "hcl"
	Yml  = "yml"
	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 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 GetBool

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

GetBool

func GetInt

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

GetInt

func GetInt64 added in v1.0.3

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

GetInt64

func GetIntArr added in v1.0.3

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

GetIntArr get config data as a int slice/array

func GetIntMap added in v1.0.3

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

GetIntMap get config data as a map[string]int

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

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

GetInt64

func (*Config) GetIntArr added in v1.0.3

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

GetIntArr get config data as a int slice/array

func (*Config) GetIntMap added in v1.0.3

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

GetIntMap get config data as a map[string]int

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