Golang配置文件解析-oozgconf

oozgconf是一款基于Golang开发的轻量级配置文件工具,支持.json、.toml、.xml、.yaml等格式的配置文件读取与解析。通过简单的API调用即可获取配置信息,适用于各种后端项目。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码地址如下:
http://www.demodashi.com/demo/14411.html

简介

oozgconf基于Golang开发,用于项目中配置文件的读取以及加载,是一个轻量级的配置文件工具。

功能

  1. 配置文件读取
  2. 配置文件解析

支持配置文件格式

  • .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

代码地址如下:
http://www.demodashi.com/demo/14411.html

注:本文著作权归作者,由demo大师发表,拒绝转载,转载需要作者授权

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值