golang解析ini文件

5年以前  |  阅读数:520 次  |  编程语言:Golang 

.ini 文件是Initialization File的缩写,即初始化文件,是windows的系统配置文件所采用的存储格式,统管windows的各项配置,一般用户就用windows提供的各项图形化管理界面就可实现相同的配置了。但在某些情况,还是要直接编辑ini才方便,一般只有很熟悉windows才能去直接编辑。

NI文件由节、键、值组成:

  • 节:节是一系列Key(键),Value(值)的集合
  • 参数:一个参数表示一个键值对
  • 注解:凡以;开始的某一行,表示这是一行注释。

ini解析类

package goconfig

import (
    "io/ioutil"
    "log"
    "strings"
)

var globalSection = "____GLOBAL____"

type IniReader struct {
    _defaultContent map[string]string
    _iniContent     map[string]interface{}
}

func NewIniReader() *IniReader {
    return &IniReader{}
}

func (self *IniReader) GetSectionValues(section string) map[string]string {
    if val, ok := self._iniContent[section]; ok {
        return val.(map[string]string)
    }
    return nil
}

func (self *IniReader) GetGlobalKey(key string) *string {
    if v, ok := self._defaultContent[key]; ok {
        return &v
    }
    return nil
}

func (self *IniReader) GetSectionKey(section, key string) *string {
    keyVals := self.GetSectionValues(section)
    if v, ok := keyVals[key]; ok {
        return &v
    }
    return nil
}

// LoadConfig 加载配置文件
func (self *IniReader) LoadIni(filePath string) bool {
    keyVals := self.loadIni(filePath)
    self._iniContent = keyVals
    self._defaultContent = self.GetSectionValues(globalSection)

    if keyVals == nil || len(keyVals) == 0 {
        log.Println("the content for the config is nil!")
        return true
    }

    return true
}

func (self *IniReader) loadIni(filePath string) map[string]interface{} {
    result := make(map[string]interface{})

    buf, err := ioutil.ReadFile(filePath)
    if err != nil {
        log.Panic("can not found the ini config at ", filePath)
    }

    content := string(buf)

    lines := strings.Split(content, "\n")
    if len(lines) == 0 {
        return result
    }

    currentSection := globalSection
    currentArr := make(map[string]string, 0)
    for _, line := range lines {
        line = strings.Replace(line, "\r", "", -1)
        line = strings.TrimSpace(line)
        if len(line) == 0 {
            continue
        }

        if strings.HasPrefix(line, "#") {
            continue
        }

        if strings.HasPrefix(line, "[") {
            if strings.HasSuffix(line, "]") {
                tempSection := line[1 : len(line)-1]
                if len(tempSection) == 0 {
                    // 容错,空section
                    continue
                }

                // 上一个section 保存
                result[currentSection] = currentArr

                currentSection = line[1 : len(line)-1]
                currentArr = make(map[string]string, 0)
                continue
            } else {
                log.Panic("INI File is not valid, wrong section")
            }
        }

        pos := strings.Index(line, "=")
        if pos > 0 && pos < len(line)-1 {
            key := line[:pos]
            val := line[pos+1:]

            key = strings.TrimSpace(key)
            val = strings.TrimSpace(val)

            currentArr[key] = val
        }
    }

    result[currentSection] = currentArr

    return result
}

用法与示例

iniReader := NewIniReader()
if iniReader.LoadIni(path) {
    // read sections and keys
}

以上代码来自开源工程:https://github.com/hello-bytes/goconfig

 相关文章:
PHP分页显示制作详细讲解
SSH 登录失败:Host key verification failed
将二进制数据转为16进制以便显示
获取IMSI
获取IMEI
Java生成UUID
PHP自定义函数获取搜索引擎来源关键字的方法
让你成为最历害的git提交人
在Zeus Web Server中安装PHP语言支持
指定应用ID以获取对应的应用名称
再谈PHP中单双引号的区别详解
Python 2与Python 3版本和编码的对比
php+ajax+json 详解及实例代码
Yii2汉字转拼音类的实例代码
php封装的page分页类完整实例
php数组合并array_merge()函数使用注意事项
PHP实现简单爬虫的方法
PHP设计模式之工厂模式与单例模式
php实现数组中索引关联数据转换成json对象的方法
wget使用技巧