Golang配置文件解析-oozgconf
阿新 • • 發佈:2019-03-05
地址 block 例程 img 需要 自動 代碼 文件讀取 格式
代碼地址如下:
http://www.demodashi.com/demo/14411.html
簡介
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
代碼地址如下:
http://www.demodashi.com/demo/14411.html
註:本文著作權歸作者,由demo大師代發,拒絕轉載,轉載需要作者授權
Golang配置文件解析-oozgconf