博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
golang下使用ini配置文件(widuu/goini)
阅读量:6396 次
发布时间:2019-06-23

本文共 5569 字,大约阅读时间需要 18 分钟。

在“widuu/goini”基础上进行了修改,增加了其他数据类型配置值(string、int、int32、int64、[]int、[]string)的支持。

 

使用方法:

ConfigCentor := goini.SetConfig("./config.ini")
读取int配置值:ConfigCentor.GetValueInt("ES","LogLevel") 读取string配置值:ConfigCentor.GetValue("ES","Url") 读取int数组配置值(","为分隔符):ConfigCentor.GetValueArray("ES","Url")

 

源码lib包(包名:goini,在go的src下创建目录goini,创建conf.go文件放在此目录即可):

package goiniimport (    "bufio"    "fmt"    "io"    "os"    "strings"    "strconv")type Config struct {    filepath string                             conflist []map[string]map[string]string }//Create empty filefunc SetConfig(filepath string) *Config {    c := new(Config)    c.filepath = filepath    return c}//key values:stringfunc (c *Config) GetValue(section, name string) string {    c.ReadList()    conf := c.ReadList()    for _, v := range conf {        for key, value := range v {            if key == section {                return value[name]            }        }    }    return ""}//key values:intfunc (c *Config) GetValueInt(section, name string) int {    c.ReadList()    conf := c.ReadList()    for _, v := range conf {        for key, value := range v {            if key == section {                val,_ := strconv.Atoi(value[name])                return val            }        }    }    return 0}//key values:intfunc (c *Config) GetValueInt32(section, name string) int32 {    c.ReadList()    conf := c.ReadList()    for _, v := range conf {        for key, value := range v {            if key == section {                val,_:=strconv.ParseInt(value[name],10,32)                return int32(val)            }        }    }    return 0}//key values:intfunc (c *Config) GetValueInt64(section, name string) int64 {    c.ReadList()    conf := c.ReadList()    for _, v := range conf {        for key, value := range v {            if key == section {                val,_:=strconv.ParseInt(value[name],10,64)                return val            }        }    }    return 0}//key values:[]int,split by ","func (c *Config) GetValueArray(section, name string) []string {    c.ReadList()    conf := c.ReadList()    for _, v := range conf {        for key, value := range v {            if key == section {                arr := strings.Split(value[name], ",")                return arr            }        }    }    return nil}//key values:[]int,split by ","func (c *Config) GetValueIntArray(section, name string) []int {    c.ReadList()    conf := c.ReadList()    for _, v := range conf {        for key, value := range v {            if key == section {                arr := strings.Split(value[name], ",")                arrValue := []int{}                 for _, str := range arr {                     val,_:=strconv.Atoi(str)                     arrValue=append(arrValue,val)                 }                return arrValue            }        }    }    return nil}//Set the corresponding value of the key value, if not add, if there is a key changefunc (c *Config) SetValue(section, key, value string) bool {    c.ReadList()    data := c.conflist    var ok bool    var index = make(map[int]bool)    var conf = make(map[string]map[string]string)    for i, v := range data {        _, ok = v[section]        index[i] = ok    }    i, ok := func(m map[int]bool) (i int, v bool) {        for i, v := range m {            if v == true {                return i, true            }        }        return 0, false    }(index)    if ok {        c.conflist[i][section][key] = value        return true    } else {        conf[section] = make(map[string]string)        conf[section][key] = value        c.conflist = append(c.conflist, conf)        return true    }    return false}//Delete the corresponding key valuesfunc (c *Config) DeleteValue(section, name string) bool {    c.ReadList()    data := c.conflist    for i, v := range data {        for key, _ := range v {            if key == section {                delete(c.conflist[i][key], name)                return true            }        }    }    return false}//List all the configuration filefunc (c *Config) ReadList() []map[string]map[string]string {    file, err := os.Open(c.filepath)    if err != nil {        CheckErr(err)    }    defer file.Close()    var data map[string]map[string]string    var section string    buf := bufio.NewReader(file)    for {        l, err := buf.ReadString('\n')        line := strings.TrimSpace(l)        if err != nil {            if err != io.EOF {                CheckErr(err)            }            if len(line) == 0 {                break            }        }        switch {        case len(line) == 0:        case line[0] == '[' && line[len(line)-1] == ']':            section = strings.TrimSpace(line[1 : len(line)-1])            data = make(map[string]map[string]string)            data[section] = make(map[string]string)        default:            i := strings.IndexAny(line, "=")            value := strings.TrimSpace(line[i+1 : len(line)])            data[section][strings.TrimSpace(line[0:i])] = value            if c.uniquappend(section) == true {                c.conflist = append(c.conflist, data)            }        }    }    return c.conflist}func CheckErr(err error) string {    if err != nil {        return fmt.Sprintf("Error is :'%s'", err.Error())    }    return "Notfound this error"}//Ban repeated appended to the slice methodfunc (c *Config) uniquappend(conf string) bool {    for _, v := range c.conflist {        for k, _ := range v {            if k == conf {                return false            }        }    }    return true}

 

转载于:https://www.cnblogs.com/lijunhao/p/5952216.html

你可能感兴趣的文章
Python3-socket网络知识储备
查看>>
Jmeter教程 简单的压力测试(Z)
查看>>
人月神话阅读笔记02
查看>>
java zip压缩优化版 解决压缩后文件一直被占用无法删除
查看>>
指定Toast显示时长(通过线程)
查看>>
Python-列表
查看>>
UVA 11181 Probability|Given (离散概率)
查看>>
如何在Less中使用使用calc
查看>>
一个完整openlayer的例子,包括marker,popup等
查看>>
机器学习入门17 - 嵌套 (Embedding)
查看>>
[08]项目实战-PC 端固定布局(8)
查看>>
shell 中的流程控制关键字
查看>>
易宝支付Demo,生产中封装成简洁的代付接口,不用request如何获取项目运行时的真实路径...
查看>>
[摘录]知彼解己—同理心交流的原则
查看>>
TCP的拥塞控制
查看>>
正则表达式
查看>>
大话GC菜鸟系列
查看>>
2. 路由事件 简单理解
查看>>
四个bug对你的好处
查看>>
6月6日进度
查看>>