Go语言(十七) 配置文件库项目
2021-01-30 05:14
标签:功能 server import data 库项目 type 异常 展开 去掉注释 Go语言(十七) 配置文件库项目 标签:功能 server import data 库项目 type 异常 展开 去掉注释 原文地址:https://blog.51cto.com/13812615/2492150简介
;config file
[server]
host = www.baidu.com
port = 8080
[cartdb]
user = root.xxx
password = root
host = localhost
port = 3306
database = cartdb
rate = 1.2
需求分析
-包含配置文件读取(UnMarshalFile)和写入(MarsharFile)两个功能代码部分
package oconfig
import (
"fmt"
"io/ioutil"
"reflect"
"strconv"
"strings"
)
func UnMarshal(data []byte,result interface{}) (err error) {
t := reflect.TypeOf(result)
v := reflect.ValueOf(result)
_ = v
kind := t.Kind()
//输入校验
if kind != reflect.Ptr {
panic("please input a address")
}
//解析配置文件
var sectionName string
lines := strings.Split(string(data),"\n")
lineNo := 0
for _,line := range lines {
lineNo ++
//去掉首位空串
line = strings.Trim(line,"\t\n\r")
if len(line) == 0 {
//空行处理
continue
}
//去掉注释
if line[0] == ‘#‘ || line[0] == ‘;‘ {
continue
}
// 解析group
if line[0] == ‘[‘ {
//解析group的名称,是否以[]包含校验
if len(line) 0 {
sectionName = tField.Tag.Get("ini")
}
//使用[]拼接sectionName
sectionName = fmt.Sprintf("[%s]\n",sectionName)
//保存sectionName信息
strSlice = append(strSlice,sectionName)
for j:=0;j
测试用例
package main
import (
"fmt"
"oldBoy/oconfig"
)
type Config struct {
Server ServerConf `ini:"server"`
CartDb DbConf `ini:"cartdb"`
}
type ServerConf struct {
Host string `ini:"host"`
Port int `ini:"port"`
}
type DbConf struct {
User string `ini:"user"`
Password string `ini:"password"`
Host string `ini:"host"`
Port int `ini:"port"`
Database string `ini:"database"`
Rate float32 `ini:"rate"`
}
func main() {
var config Config
filename := "./example.ini"
//config要传入地址(引用类型)
err := oconfig.UnMarshalFile(filename,&config)
if err != nil {
fmt.Printf("unmarshal file faild,err:%v\n",err)
return
}
fmt.Printf("conf=%#v\n",config)
oconfig.MarshalFile("./aaa.ini",config)
}
;config file
[server]
host = www.baidu.com
port = 8080
#DB Config
[cartdb]
user = root.xxx.sss
password = root
host = localhost
port = 3306
database = cartdb
rate = 1.23456