Ai
1 Star 0 Fork 0

技术狼/go-config

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
config_file.go 1.99 KB
一键复制 编辑 原始数据 按行查看 历史
技术狼 提交于 2024-10-09 23:43 +08:00 . v0.0.4
package config
import (
"bytes"
"encoding/json"
"fmt"
fun "gitee.com/jishulangcom/go-fun"
"github.com/BurntSushi/toml"
"gopkg.in/yaml.v3"
)
func configCreateFile(conf interface{}, configType string) {
filePath := fmt.Sprintf("%s/%s.%s", CONFIG_DIR, SETTINGS_NAME, configType)
is, _ := fun.FileIsExist(filePath)
if !is {
content := structToConfigType(conf, configType)
fun.FilePutContents(filePath, content)
}
//
for _, e := range envArr {
filePath = fmt.Sprintf("%s/%s_%s.%s", CONFIG_DIR, SETTINGS_NAME, e, configType)
is, _ = fun.FileIsExist(filePath)
if !is {
//content := structToConfigType(conf, configType)
content := contentDefaultValue(configType)
fun.FilePutContents(filePath, content)
}
}
}
func contentDefaultValue(configType string) string {
switch configType {
case CONFIG_TYPE_YAML, CONFIG_TYPE_YML:
case CONFIG_TYPE_JSON:
return "{}"
case CONFIG_TYPE_TOML:
//case "properties":
//case "props":
//case "hcl":
//case "tfvars":
//case "dotenv":
//case "env":
//case "ini":
}
return ""
}
func structToConfigType(conf interface{}, configType string) string {
var jsonBytes []byte
var err error
switch configType {
case CONFIG_TYPE_YAML, CONFIG_TYPE_YML:
jsonBytes, err = structToYaml(conf)
case CONFIG_TYPE_JSON:
jsonBytes, err = structToJson(conf)
case CONFIG_TYPE_TOML:
jsonBytes, err = structToToml(conf)
//case "properties":
//case "props":
//case "hcl":
//case "tfvars":
//case "dotenv":
//case "env":
//case "ini":
}
if err != nil {
fmt.Println("[NewConfig]structToConfigType err:", err.Error())
return ""
}
return string(jsonBytes)
}
func structToJson(conf interface{}) ([]byte, error) {
return json.MarshalIndent(conf, "", " ")
}
func structToToml(conf interface{}) ([]byte, error) {
var tomlBuffer bytes.Buffer
err := toml.NewEncoder(&tomlBuffer).Encode(conf)
if err != nil {
return nil, err
}
return tomlBuffer.Bytes(), nil
}
func structToYaml(conf interface{}) ([]byte, error) {
return yaml.Marshal(conf)
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/jishulang/go-config.git
git@gitee.com:jishulang/go-config.git
jishulang
go-config
go-config
v0.0.4

搜索帮助