golang 解析 ini文件

目录结构

golang 解析 ini文件_第1张图片

ini文件解析

打开 iniParser.go

package parserPool

import (
	"os"
	"fmt"
	"strings"
)

type IniParser struct {
	FileName string
	IM map[string]map[string]string
}



func (iniP *IniParser)ParserIniFile(fileName string) {
	defer func() {
		if err := recover();err != nil{
			fmt.Println("parser File Failed" ,err)
		}

	}()

	iniP.FileName  = fileName
	iniP.IM = map[string]map[string]string{}
	buf := make ([]byte,1)
	file, e := os.Open(iniP.FileName)
	if e != nil{
		fmt.Println( e.Error())
	}
	var line string
	//iM := iniMap{}
	partName :="global"
	iniP.IM[partName] = map[string]string{}
	for n, err := file.Read(buf) ; n > 0 ;  n, err = file.Read(buf) {
		if err != nil{
			fmt.Println("read file failed : %s ",e.Error())
			break
		}
		if string(buf) =="\n"{
			iCode, str := parserIniLine(line)
			switch iCode {
			case 1:
				partName = str
				iniP.IM[partName] = map[string]string{}
			case 2:
				aName := strings.Split(str,"=")[0]
				aValue := strings.Split(str,"=")[1]

				iniP.IM[partName][aName] = aValue

			}
			line = ""
		}else {
			line += string(buf)
		}

	}


}


func parserIniLine(line string) (int ,string){
	cmtIdx := strings.Index(line,";")
	if cmtIdx > 0{
		line = strings.Split(line, ";")[0]
	}
	brackets_left := strings.Index(line,"[")
	brackets_right := strings.Index(line,"]")

	if brackets_left >= 0 && brackets_right >brackets_left{
		line = strings.Split(line,"[")[1]
		line = strings.Split(line,"]")[0]
		return  1,line
	}
	if brackets_left < 0 && brackets_right < 0 &&strings.Contains(line,"=") {
		return 2,line
	}

	return 0,""
}

func (iniP *IniParser) GetName(pName string,vName string) string{
	return iniP.IM[pName][vName]
}

main

package main

import (
	"../code/fileParser/parserPool"
	"fmt"
)

func main() {

	IniParser := new(parserPool.IniParser)
	IniParser.ParserIniFile("./fileParser/file_source/test.ini")
	value  := IniParser.GetName("global", "appName")
	value1  := IniParser.GetName("server", "host")
	fmt.Println(value)
	fmt.Println(value1)
}

test.ini

[global]
appName="222"

[server]
host="sss"

运行结果

golang 解析 ini文件_第2张图片

你可能感兴趣的:(golang)