1 Star 0 Fork 0

myzero1/gotool

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
z1cnf.go 2.16 KB
一键复制 编辑 原始数据 按行查看 历史
myzero1 提交于 2022-09-14 00:52 . fix z1cnf
package z1cnf
import (
"bytes"
"io/ioutil"
"os"
"path/filepath"
"gitee.com/myzero1/gotool/z1err"
"gitee.com/myzero1/gotool/z1log"
"github.com/spf13/viper"
"go.uber.org/zap"
)
var Z1viper *viper.Viper
const (
YAML int8 = iota
JSON
)
func init() {
Z1viper = viper.New()
}
func Init(contentType int8, fileName, content string) {
// Init(z1cnf.JSON, `config/config.yaml`, `{"contentType":"json","name":"张三","年龄":18}`)
// Init(YAML, `config/config.yaml`, `
// 成绩:
// 张三: 90
// 李四: 95
// 班级: 一年级
// 老师: # 数学老师和语文老师
// - 张老师
// - 李老师`)
Z1viper.SetConfigFile(fileName)
Z1viper.SetConfigType("yaml")
Z1viper.WatchConfig()
_, err := os.Lstat(fileName)
if os.IsNotExist(err) {
dir := filepath.Dir(fileName)
os.MkdirAll(dir, 0666)
f, err := os.Create(fileName)
z1err.Check(err)
if contentType == JSON {
{
// j := []byte(content)
// // j := []byte(`{"name": "John", "age": 30}`)
// y, err := yaml.JSONToYAML(j)
// // j2, err := yaml.YAMLToJSON(y)
// z1err.Check(err)
// f.WriteString(string(y))
}
{
content2 := Convert(`json`, content, `yaml`)
f.WriteString(content2)
}
} else {
f.WriteString(content)
}
f.Close()
z1err.Check(Z1viper.ReadInConfig())
z1log.Info(`"z1cnf" is initialized successfully. Please adjust the configuration file and run again.`, zap.String(`fileName`, fileName))
} else {
z1err.Check(Z1viper.ReadInConfig())
z1log.Info(`"z1cnf" has been initialized. If you need to re initialize, please delete the configuration file first.`, zap.String(`fileName`, fileName))
}
}
func Convert(sourceType, sourceContent, targetType string) (targetContent string) {
sviper := viper.New()
sviper.SetConfigType(sourceType)
j := []byte(sourceContent)
z1err.Check(sviper.ReadConfig(bytes.NewBuffer(j)))
tviper := viper.New()
tviper.SetConfigType(targetType)
tviper.Set(`data`, sviper.AllSettings())
subViper := tviper.Sub(`data`)
tmpfile := os.TempDir() + `z1cnfConvert.` + targetType
z1err.Check(subViper.WriteConfigAs(tmpfile))
b, err := ioutil.ReadFile(tmpfile)
z1err.Check(err)
targetContent = string(b)
return
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/myzero1/gotool.git
git@gitee.com:myzero1/gotool.git
myzero1
gotool
gotool
v0.8.2

搜索帮助

23e8dbc6 1850385 7e0993f3 1850385