2 Star 1 Fork 1

qiqi / cfg

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
cfg.go 9.75 KB
一键复制 编辑 原始数据 按行查看 历史
qiqi 提交于 2023-12-05 11:55 +08:00 . 配置支持环境变量替换能力
package cfg
import (
"errors"
"github.com/BurntSushi/toml"
"github.com/fsnotify/fsnotify"
"github.com/mitchellh/mapstructure"
"gopkg.in/yaml.v3"
"os"
"path/filepath"
"reflect"
"regexp"
"strings"
"time"
)
// 配置对象
type Handler struct {
Source string
ConfType string
confInfo interface{}
path string
dynamic bool
}
// New default get a cfg handler by file path and not open dynamic
func New(filePath string) *Handler {
return NewFile(filePath, false)
}
// NewFile get a cfg handler by file path
func NewFile(filePath string, dynamic bool) *Handler {
if filePath == "" {
return nil
}
var err error
filePath, err = filepath.Abs(filePath)
if err != nil {
panic(err)
}
confFileType := strings.Trim(filepath.Ext(filePath), ".")
handler := Handler{
ConfType: confFileType,
Source: "file",
path: filePath,
dynamic: dynamic,
}
content, err := os.ReadFile(filePath)
if err != nil {
panic(err)
}
// 替换环境变量字符
envContent := replaceEnvVars(string(content))
switch confFileType {
case "toml":
if _, err := toml.Decode(envContent, &handler.confInfo); err != nil {
panic(err)
}
case "yml", "yaml":
if err := yaml.Unmarshal([]byte(envContent), &handler.confInfo); err != nil {
panic(err)
}
default:
panic("can not support this type config file:" + confFileType)
}
if dynamic {
go handler.watchContent()
}
return &handler
}
// NewTomlData get a cfg handler by toml string content
func NewTomlData(content string) *Handler {
if content == "" {
return nil
}
handler := Handler{ConfType: "toml", Source: "content"}
// 替换环境变量字符
envContent := replaceEnvVars(content)
if _, err := toml.Decode(envContent, &handler.confInfo); err != nil {
panic(err)
}
return &handler
}
// ReloadTomlData get a cfg handler by toml string content
func ReloadTomlData(content string) (*Handler, error) {
if content == "" {
return nil, errors.New("config content is empty")
}
handler := Handler{ConfType: "toml", Source: "content"}
// 替换环境变量字符
envContent := replaceEnvVars(content)
if _, err := toml.Decode(envContent, &handler.confInfo); err != nil {
return nil, err
}
return &handler, nil
}
// NewTomlData get a cfg handler by toml string content
func NewYamlData(content string) *Handler {
if content == "" {
return nil
}
handler := Handler{ConfType: "yaml", Source: "content"}
// 替换环境变量字符
envContent := replaceEnvVars(content)
if err := yaml.Unmarshal([]byte(envContent), &handler.confInfo); err != nil {
panic(err)
}
return &handler
}
// ReloadYamlData get a cfg handler by toml string content
func ReloadYamlData(content string) (*Handler, error) {
if content == "" {
return nil, errors.New("config content is empty")
}
// 替换环境变量字符
envContent := replaceEnvVars(content)
handler := Handler{ConfType: "yaml", Source: "content"}
if err := yaml.Unmarshal([]byte(envContent), &handler.confInfo); err != nil {
return nil, err
}
return &handler, nil
}
// StartDynamic after start listen config file change
func (c *Handler) StartDynamic() *Handler {
if c.dynamic == true {
return c
}
c.dynamic = true
go c.watchContent()
return c
}
// ReloadFile get a cfg handler by file path reload config
func (c *Handler) ReloadFile() *Handler {
if c.path == "" {
return nil
}
var configContent interface{}
content, err := os.ReadFile(c.path)
if err != nil {
panic(err)
}
// 替换环境变量字符
envContent := replaceEnvVars(string(content))
switch c.ConfType {
case "toml":
if _, err := toml.Decode(envContent, &configContent); err != nil {
panic(err)
}
case "yml", "yaml":
if err := yaml.Unmarshal([]byte(envContent), &configContent); err != nil {
panic(err)
}
default:
panic("can not support this type config file:" + c.ConfType)
}
c.confInfo = configContent
return c
}
// WatchConfig
func (c *Handler) watchContent() {
if c.path == "" {
return
}
watcher, err := newWatcher()
defer watcher.Close()
if err != nil {
panic(err)
}
done := make(chan bool)
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok { // 'Events' channel is closed
return
}
const writeOrCreateMask = fsnotify.Write | fsnotify.Create
if filepath.Clean(event.Name) == filepath.Clean(c.path) &&
event.Op&writeOrCreateMask != 0 {
c.ReloadFile()
}
}
}
}()
watcher.Add(c.path)
<-done
}
// UnmarshalKey Unmarshal config to struct
func (c *Handler) UnmarshalKey(key string, rawVal interface{}) error {
ret := c.ParseNode(key)
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
TagName: "json",
Metadata: nil,
Result: rawVal,
})
if err != nil {
return err
}
return decoder.Decode(ret)
}
// GetString get config string type
func (c *Handler) GetString(key string) string {
ret := c.ParseNode(key)
showRet, ok := ret.(string)
if ok != true {
return ""
}
return showRet
}
// GetInt get config int type
func (c *Handler) GetInt(key string) int {
ret := c.ParseNode(key)
if c.ConfType == "toml" {
showRet, ok := ret.(int64)
if ok != true {
return 0
}
return int(showRet)
}
showRet, ok := ret.(int)
if ok != true {
return 0
}
return int(showRet)
}
// GetInt64 get config int64 type
func (c *Handler) GetInt64(key string) int64 {
ret := c.ParseNode(key)
if c.ConfType == "toml" {
showRet, ok := ret.(int64)
if ok != true {
return 0
}
return int64(showRet)
}
showRet, ok := ret.(int)
if ok != true {
return 0
}
return int64(showRet)
}
// GetBool get config bool type
func (c *Handler) GetBool(key string) bool {
ret := c.ParseNode(key)
showRet, ok := ret.(bool)
if ok != true {
return false
}
return showRet
}
// GetDuration get config time.Duration type
func (c *Handler) GetDuration(key string) time.Duration {
ret := c.GetInt64(key)
showRet := time.Duration(ret)
return showRet
}
// GetSliceInt get slice int type
func (c *Handler) GetSliceInt(key string) []int {
slice := c.getSlice(key)
showRet := make([]int, 0)
if len(slice) == 0 {
return showRet
}
for _, item := range slice {
switch item.(type) {
case int64:
value, ok := item.(int64)
if ok != true {
break
}
showRet = append(showRet, int(value))
case int:
value, ok := item.(int)
if ok != true {
break
}
showRet = append(showRet, int(value))
}
}
return showRet
}
// GetSliceInt64 get slice int64 type
func (c *Handler) GetSliceInt64(key string) []int64 {
slice := c.getSlice(key)
showRet := make([]int64, 0)
if len(slice) == 0 {
return showRet
}
for _, item := range slice {
switch item.(type) {
case int64:
value, ok := item.(int64)
if ok != true {
break
}
showRet = append(showRet, int64(value))
case int:
value, ok := item.(int)
if ok != true {
break
}
showRet = append(showRet, int64(value))
}
}
return showRet
}
// GetSliceString get slice string type
func (c *Handler) GetSliceString(key string) []string {
slice := c.getSlice(key)
showRet := make([]string, 0)
if len(slice) == 0 {
return showRet
}
for _, item := range slice {
value, ok := item.(string)
if ok != true {
break
}
showRet = append(showRet, value)
}
return showRet
}
// GetMap parse config node to map
func (c *Handler) GetMap(parse string) map[string]interface{} {
nodeParse := strings.Split(parse, ".")
var ret interface{}
ret = c.confInfo
for _, item := range nodeParse {
ret = readNode(item, ret)
}
if mapRet, ok := ret.(map[string]interface{}); ok {
return mapRet
}
if mapIRet, ok := ret.(map[interface{}]interface{}); ok {
mapRet := make(map[string]interface{})
for k, item := range mapIRet {
if mapKey, ok := k.(string); ok == true {
mapRet[mapKey] = item
}
}
return mapRet
}
return nil
}
// ParseNode parse config node
func (c *Handler) ParseNode(parse string) (ret interface{}) {
nodeParse := strings.Split(parse, ".")
ret = c.confInfo
for _, item := range nodeParse {
ret = readNode(item, ret)
}
return
}
// Exists find config node exists
func (c *Handler) Exists(parse string) bool {
nodeParse := strings.Split(parse, ".")
var ret interface{}
var exists bool
ret = c.confInfo
for _, item := range nodeParse {
exists, ret = readExistsNode(item, ret)
}
return exists
}
// getSlice get config slice []interface{} type
func (c *Handler) getSlice(key string) []interface{} {
ret := c.ParseNode(key)
slice, ok := ret.([]interface{})
if ok != true {
return []interface{}{}
}
return slice
}
// readNode ...
func readNode(key string, node interface{}) (ret interface{}) {
if node == nil {
return
}
nodeType := reflect.TypeOf(node).String()
if nodeType == "map[string]interface {}" {
nodeInfo := node.(map[string]interface{})
return nodeInfo[key]
}
if nodeType == "map[interface {}]interface {}" {
nodeInfo := node.(map[interface{}]interface{})
return nodeInfo[key]
}
return node
}
// readExistsNode ...
func readExistsNode(key string, node interface{}) (exists bool, ret interface{}) {
if node == nil {
return
}
nodeType := reflect.TypeOf(node).String()
if nodeType == "map[string]interface {}" {
nodeInfo := node.(map[string]interface{})
if _, ok := nodeInfo[key]; ok {
return true, nodeInfo[key]
}
return false, nodeInfo[key]
}
if nodeType == "map[interface {}]interface {}" {
nodeInfo := node.(map[interface{}]interface{})
if _, ok := nodeInfo[key]; ok {
return true, nodeInfo[key]
}
return false, nodeInfo[key]
}
return false, node
}
func replaceEnvVars(content string) (replacedStr string) {
pattern := "\\$\\{[A-Za-z0-9_]+\\}"
re := regexp.MustCompile(pattern)
replacedStr = re.ReplaceAllStringFunc(content, func(match string) string {
envVarName := match[2 : len(match)-1] // Remove ${ and }
envVarValue := os.Getenv(envVarName)
if envVarValue != "" {
return filepath.ToSlash(envVarValue)
}
return match
})
return
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/zhucheer/cfg.git
git@gitee.com:zhucheer/cfg.git
zhucheer
cfg
cfg
v0.2.1

搜索帮助

⌂ 换网址