Golang配置文件解析-oozgconf
简介
oozgconf基于Golang开发,用于项目中配置文件的读取以及加载,是一个轻量级的配置文件工具。
功能
- 配置文件读取
- 配置文件解析
支持配置文件格式
- .json
- .toml
- .xml
- .yaml
安装
$ go get -u github.com/usthooz/oozgconf
实现思路
在后端项目中,配置文件已经是一个不可或缺的东西了,格式也是多种多样。
流程结构
如下图所示为项目实现流程及结构:
代码目录结构
主要代码
- 配置文件后缀名常量定义
const (
JsonSub string = "json"
YamlSub string = "yaml"
TomlSub string = "toml"
XmlSub string = "xml"
)
- 对象结构
type OozGconf struct {
// ConfPath config file path->default: ./config/config.yaml
ConfPath string
// Subffix config file subffix
Subffix string
}
- 新建gconf对象
在使用时,如果不指定配置文件的路径,那么默认为./config/config.yaml,同时如果不指定文件类型,则自动通过解析文件名来获得配置文件的后缀。
// NewConf new conf object
func NewConf(confParam *OozGconf) *OozGconf {
if len(confParam.ConfPath) == 0 {
confParam.ConfPath = "./config/config.yaml"
}
return confParam
}
- 获取配置
/*
confpath: config file path->default: ./config/config.yaml
subffix: config file subffie->option
*/
func (oozConf *OozGconf) GetConf(conf interface{}) error {
// read config file
bs, err := ioutil.ReadFile(oozConf.ConfPath)
if err != nil {
return err
}
if len(oozConf.Subffix) == 0 {
// get file subffix
oozConf.Subffix = strings.Trim(path.Ext(path.Base(oozConf.ConfPath)), ".")
}
// check analy
switch oozConf.Subffix {
case JsonSub:
err = json.Unmarshal(bs, conf)
case TomlSub:
err = toml.Unmarshal(bs, conf)
case YamlSub:
err = yaml.Unmarshal(bs, conf)
case XmlSub:
err = xml.Unmarshal(bs, conf)
default:
err = fmt.Errorf("GetConf: non support this file type...")
}
return err
}
使用例程
- example
import (
"github.com/usthooz/oozgconf"
"github.com/usthooz/oozlog/go"
)
type Config struct {
Author string
Mysql struct {
User string
Password string
}
}
func main() {
var (
conf Config
)
// new conf object
ozconf := oozgconf.NewConf(&oozgconf.OozGconf{
ConfPath: "./config.json", // 可选,默认为./config/config.yaml
Subffix: "", // 可选,如果不指定则自动解析文件名获取
})
// get config
err := ozconf.GetConf(&conf)
if err != nil {
uoozg.Errorf("GetConf Err: %v", err.Error())
}
uoozg.Infof("Res: %v", conf)
}
运行结果
其他
没有
Golang配置文件解析-oozgconf
注:本文著作权归作者,由demo大师代发,拒绝转载,转载需要作者授权
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?