All Projects → gookit → Config

gookit / Config

Licence: mit
📝 Go config manage(load,get,set). support JSON, YAML, TOML, INI, HCL, ENV and Flags. Multi file load, data override merge, parse ENV var. Go应用配置加载管理,支持多种格式,多文件加载,远程文件加载,支持数据合并,解析环境变量名

Programming Languages

go
31211 projects - #10 most used programming language

Projects that are alternatives of or similar to Config

parse it
A python library for parsing multiple types of config files, envvars & command line arguments that takes the headache out of setting app configurations.
Stars: ✭ 86 (-61.78%)
Mutual labels:  config, yaml, toml, hcl, ini
Structured Text Tools
A list of command line tools for manipulating structured text data
Stars: ✭ 6,180 (+2646.67%)
Mutual labels:  json, yaml, toml, ini
Configr
Implements the JSON, INI, YAML and TOML parser, for R setting and writing of configuration file.
Stars: ✭ 38 (-83.11%)
Mutual labels:  json, yaml, toml, ini
Ansible Config encoder filters
Ansible role used to deliver the Config Encoder Filters.
Stars: ✭ 48 (-78.67%)
Mutual labels:  json, yaml, toml, ini
Dasel
Query, update and convert data structures from the command line. Comparable to jq/yq but supports JSON, TOML, YAML, XML and CSV with zero runtime dependencies.
Stars: ✭ 759 (+237.33%)
Mutual labels:  config, json, yaml, toml
Simple Settings
A simple way to manage your project settings.
Stars: ✭ 165 (-26.67%)
Mutual labels:  config, json, yaml, toml
Mconfig
MCONFIG is a lightweight Golang library for integrating configs files like (json, yml, toml) and environment variables into one config struct.
Stars: ✭ 28 (-87.56%)
Mutual labels:  config, json, yaml, toml
transfer
Converts from one encoding to another. Supported formats HCL ⇄ JSON ⇄ YAML⇄TOML⇄XML⇄plist⇄pickle⇄properties ...
Stars: ✭ 70 (-68.89%)
Mutual labels:  config, yaml, toml, hcl
Konf
A type-safe cascading configuration library for Kotlin/Java/Android, supporting most configuration formats
Stars: ✭ 225 (+0%)
Mutual labels:  config, json, yaml, toml
Resticprofile
Configuration profiles for restic backup
Stars: ✭ 48 (-78.67%)
Mutual labels:  hcl, json, yaml, toml
Config Rs
⚙️ Layered configuration system for Rust applications (with strong support for 12-factor applications).
Stars: ✭ 915 (+306.67%)
Mutual labels:  config, config-management, json, toml
Config
PHP library for simple configuration management
Stars: ✭ 39 (-82.67%)
Mutual labels:  config, yaml, config-management, ini
Cfgdiff
diff(1) all your configs
Stars: ✭ 138 (-38.67%)
Mutual labels:  config, json, yaml, ini
Ini Parser
Read/Write an INI file the easy way!
Stars: ✭ 643 (+185.78%)
Mutual labels:  config, config-management, ini
Koanf
Light weight, extensible configuration management library for Go. Built in support for JSON, TOML, YAML, env, command line, file, S3 etc. Alternative to viper.
Stars: ✭ 450 (+100%)
Mutual labels:  config, yaml, toml
Re Txt
converts text-formats from one to another, it is very useful if you want to re-format a json file to yaml, toml to yaml, csv to yaml, ... etc
Stars: ✭ 59 (-73.78%)
Mutual labels:  json, yaml, toml
Config Lite
A super simple & flexible & useful config module.
Stars: ✭ 78 (-65.33%)
Mutual labels:  config, yaml, toml
Config Lint
Command line tool to validate configuration files
Stars: ✭ 118 (-47.56%)
Mutual labels:  hcl, json, yaml
Datafiles
A file-based ORM for Python dataclasses.
Stars: ✭ 113 (-49.78%)
Mutual labels:  json, yaml, toml
Rq
Record Query - A tool for doing record analysis and transformation
Stars: ✭ 1,808 (+703.56%)
Mutual labels:  json, yaml, toml

Config

GitHub go.mod Go version Codacy Badge GoDoc Build Status Actions Status Coverage Status Go Report Card

Golang's application config manage tool library.

中文说明

Features

  • Support multi format: JSON(default), INI, YAML, TOML, HCL, ENV, Flags
    • JSON content support comments. will auto clear comments
    • Other drivers are used on demand, not used will not be loaded into the application.
      • Possibility to add custom driver for your specific format
  • Support multi-file and multi-data loading
  • Support loading configuration from os ENV
  • 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 for binding all or part of the configuration data to the structure
  • Support get sub value by path, like map.key arr.2
  • Support parse ENV name and allow with default value. like envKey: ${SHELL|/bin/bash} -> envKey: /bin/zsh
  • Generic api Get Int Uint Int64 Float String Bool Ints IntMap Strings StringMap ...
  • Complete unit test(code coverage > 95%)

Provide a sub-package dotenv that supports importing data from files (eg .env) to ENV

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

// go run ./examples/yaml.go
func main() {
	config.WithOptions(config.ParseEnv)

	// add driver for support yaml content
	config.AddDriver(yaml.Driver)

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

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

Bind Structure

Note: The default binding mapping tag of a structure is mapstructure, which can be changed by setting Options.TagName

user := struct {
    Age  int  `mapstructure:"age"`
    Key  string `mapstructure:"key"`
    UserName  string `mapstructure:"user_name"`
    Tags []int  `mapstructure:"tags"`
}{}

err = config.BindStruct("user", &user)

fmt.Println(user.UserName) // inhere

Change struct tag name

config.WithOptions(func(opt *Options) {
    opt.TagName = "config"
})

Can use empty string for bind all config data to a struct:

config.BindStruct("", &myConf)

Direct Read data

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

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

Load from flags

Support simple flags parameter parsing, loading

// flags like: --name inhere --env dev --age 99 --debug

// load flag info
keys := []string{"name", "env", "age:int" "debug:bool"}
err := config.LoadFlags(keys)

// read
config.String("name") // "inhere"
config.String("env") // "dev"
config.Int("age") // 99
config.Bool("debug") // true

Load from ENV

// os env: APP_NAME=config APP_DEBUG=true
// load ENV info
config.LoadOSEnv([]string{"APP_NAME", "APP_DEBUG"}, true)

// read
config.Bool("app_debug") // true
config.String("app_name") // "config"

New Config Instance

You can create custom config instance

// create new instance, will auto register JSON driver
myConf := config.New("my-conf")

// create empty instance
myConf := config.NewEmpty("my-conf")

// create and with some options
myConf := config.NewWithOptions("my-conf", config.ParseEnv, config.ReadOnly)

Available Options

// Options config options
type Options struct {
	// parse env value. like: "${EnvName}" "${EnvName|default}"
	ParseEnv bool
	// config is readonly. default is False
	Readonly bool
	// enable config data cache. default is False
	EnableCache bool
	// parse key, allow find value by key path. default is True eg: 'key.sub' will find `map[key]sub`
	ParseKey bool
	// tag name for binding data to struct
	TagName string
	// the delimiter char for split key, when `FindByPath=true`. default is '.'
	Delimiter byte
	// default write format. default is JSON
	DumpFormat string
	// default input format. default is JSON
	ReadFormat string
}

API Methods Refer

Load Config

  • LoadOSEnv(keys []string) Load from os ENV
  • 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

  • Bool(key string, defVal ...bool) bool
  • Int(key string, defVal ...int) int
  • Uint(key string, defVal ...uint) uint
  • Int64(key string, defVal ...int64) int64
  • Ints(key string) (arr []int)
  • IntMap(key string) (mp map[string]int)
  • Float(key string, defVal ...float64) float64
  • String(key string, defVal ...string) string
  • Strings(key string) (arr []string)
  • StringMap(key string) (mp map[string]string)
  • Get(key string, findByPath ...bool) (value interface{})

Setting Values

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

Useful Methods

  • Getenv(name string, defVal ...string) (val string)
  • AddDriver(driver Driver)
  • Data() map[string]interface{}
  • SetData(data map[string]interface{}) set data to override the Config.Data
  • Exists(key string, findByPath ...bool) bool
  • DumpTo(out io.Writer, format string) (n int64, err error)
  • BindStruct(key string, dst interface{}) error

Run Tests

go test -cover
// contains all sub-folder
go test -cover ./...

Gookit packages

  • gookit/ini Go config management, use INI files
  • gookit/rux Simple and fast request router for golang HTTP
  • gookit/gcli build CLI application, tool library, running CLI commands
  • gookit/event Lightweight event manager and dispatcher implements by Go
  • gookit/cache Generic cache use and cache manager for golang. support File, Memory, Redis, Memcached.
  • gookit/config Go config management. support JSON, YAML, TOML, INI, HCL, ENV and Flags
  • gookit/color A command-line color library with true color support, universal API methods and Windows support
  • gookit/filter Provide filtering, sanitizing, and conversion of golang data
  • gookit/validate Use for data validation and filtering. support Map, Struct, Form data
  • gookit/goutil Some utils for the Go: string, array/slice, map, format, cli, env, filesystem, test and more
  • More please see https://github.com/gookit

See also

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].