2 Star 15 Fork 1

gookit / config

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
MIT

Config

Codacy Badge GoDoc Build Status Coverage Status Go Report Card

简洁、功能完善的Golang应用程序配置管理工具库

EN README

功能简介

  • 支持多种格式: JSON(默认), INI, YAML, TOML, HCL, ENV, Flags
    • JSON 内容支持注释,可以设置解析时清除注释
    • 其他驱动都是按需使用,不使用的不会加载编译到应用中
  • 支持多个文件、多数据加载
  • 支持从 OS ENV 变量数据加载配置
  • 支持从远程 URL 加载配置数据
  • 支持从命令行参数(flags)设置配置数据
  • 支持数据覆盖合并,加载多份数据时将按key自动合并
  • 支持将全部或部分配置数据绑定到结构体 config.BindStruct("key", &s)
  • 支持通过 . 分隔符来按路径获取子级值,也支持自定义分隔符。 e.g map.key arr.2
  • 支持解析ENV变量名称。 like shell: ${SHELL} -> shell: /bin/zsh
  • 简洁的使用API Get Int Uint Int64 String Bool Ints IntMap Strings StringMap ...
  • 完善的单元测试(code coverage > 95%)

提供一个子包 dotenv,支持从文件(eg .env)中导入数据到ENV

只使用INI

如果你仅仅想用INI来做简单配置管理,推荐使用 gookit/ini

GoDoc

快速使用

这里使用yaml格式作为示例(testdata/yml_other.yml):

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

map1:
    key: val2
    key2: val20

arr1:
    - val1
    - val21

载入数据

示例代码请看 _examples/yaml.go:

package main

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

// go run ./examples/yaml.go
func main() {
	// 设置选项支持 ENV 解析
	config.WithOptions(config.ParseEnv)

	// 添加驱动程序以支持yaml内容解析(除了JSON是默认支持,其他的则是按需使用)
	config.AddDriver(yaml.Driver)

	// 加载配置,可以同时传入多个文件
	err := config.LoadFiles("testdata/yml_base.yml")
	if err != nil {
		panic(err)
	}

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

	// 加载更多文件
	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)
	}
}

获取数据

// 获取整型
age := config.Int("age")
fmt.Print(age) // 100

// 获取布尔值
val := config.Bool("debug")
fmt.Print(val) // true

// 获取字符串
name := config.String("name")
fmt.Print(name) // inhere

// 获取字符串数组
arr1 := config.Strings("arr1")
fmt.Printf("%v %#v", arr1) // []string{"val1", "val21"}

// 获取字符串KV映射
val := config.StringMap("map1")
fmt.Printf("%v %#v",val) // map[string]string{"key":"val2", "key2":"val20"}

// 值包含ENV变量
value := config.String("shell")
fmt.Print(value) // /bin/zsh

// 通过key路径获取值
// from array
value := config.String("arr1.0")
fmt.Print(value) // "val1"

// from map
value := config.String("map1.key")
fmt.Print(value) // "val2"

设置新的值

// set value
config.Set("name", "new name")
// get
name = config.String("name")
fmt.Print(name) // new name

绑定数据到结构体

user := struct {
    Age  int
    Kye  string
    Tags []int
}{}
err = config.BindStruct("user", &user)

从ENV载入数据

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

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

从命令行参数载入数据

支持简单的命令行 flag 参数解析,加载数据

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

可用选项

// 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
	// 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方法参考

载入配置

  • LoadOSEnv(keys []string) 从ENV载入数据
  • LoadData(dataSource ...interface{}) (err error) 从struct或map加载数据
  • LoadFlags(keys []string) (err error) 从命令行参数载入数据
  • LoadExists(sourceFiles ...string) (err error) 从存在的配置文件里加载数据,会忽略不存在的文件
  • LoadFiles(sourceFiles ...string) (err error) 从给定的配置文件里加载数据,有文件不存在则会panic
  • LoadRemote(format, url string) (err error) 从远程 URL 加载配置数据
  • LoadSources(format string, src []byte, more ...[]byte) (err error) 从给定格式的字节数据加载配置
  • LoadStrings(format string, str string, more ...string) (err error) 从给定格式的字符串配置里加载配置数据

获取值

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

设置值

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

有用的方法

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

单元测试

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

Gookit 工具包

  • gookit/ini INI配置读取管理,支持多文件加载,数据覆盖合并, 解析ENV变量, 解析变量引用
  • gookit/rux Simple and fast request router for golang HTTP
  • gookit/gcli Go的命令行应用,工具库,运行CLI命令,支持命令行色彩,用户交互,进度显示,数据格式化显示
  • gookit/event Go实现的轻量级的事件管理、调度程序库, 支持设置监听器的优先级, 支持对一组事件进行监听
  • gookit/cache 通用的缓存使用包装库,通过包装各种常用的驱动,来提供统一的使用API
  • gookit/config Go应用配置管理,支持多种格式(JSON, YAML, TOML, INI, HCL, ENV, Flags),多文件加载,远程文件加载,数据合并
  • gookit/color CLI 控制台颜色渲染工具库, 拥有简洁的使用API,支持16色,256色,RGB色彩渲染输出
  • gookit/filter 提供对Golang数据的过滤,净化,转换
  • gookit/validate Go通用的数据验证与过滤库,使用简单,内置大部分常用验证、过滤器
  • gookit/goutil Go 的一些工具函数,格式化,特殊处理,常用信息获取等
  • 更多请查看 https://github.com/gookit

相关包

License

MIT

The MIT License (MIT) Copyright (c) 2016 inhere Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

简介

Go config manage(load,get,set). support JSON, YAML, TOML, INI, HCL. multi file load, data override merge. go应用配置加载管理,支持多种格式,多文件加载,支持数据合并. 展开 收起
Go
MIT
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Go
1
https://gitee.com/gookit/config.git
git@gitee.com:gookit/config.git
gookit
config
config
master

搜索帮助

14c37bed 8189591 565d56ea 8189591