golang 读取配置文件

unix 风格的配置文件


[default]
path= c:/go
version = 1.44
 
[test]
num =	666
something  = wrong  #注释1
#fdfdfd = fdfdfd    注释整行
refer= refer       //注释3


config.go

package conf

import (
	"bufio"
	"io"
	"os"
	"strings"
)

const middle = "========="

type Config struct {
	Mymap  map[string]string
	strcet string
}

func (c *Config) InitConfig(path string) {
	c.Mymap = make(map[string]string)

	f,err := os.Open(path)
	if err != nil {
		panic(err)
	}
	defer f.Close()

	r := bufio.NewReader(f)
	for {
		b,_,err := r.ReadLine()
		if err != nil {
			if err == io.EOF {
				break
			}
			panic(err)
		}

		s := strings.TrimSpace(string(b))
		//fmt.Println(s)
		if strings.Index(s,"#") == 0 {
			continue
		}

		n1 := strings.Index(s,"[")
		n2 := strings.LastIndex(s,"]")
		if n1 > -1 && n2 > -1 && n2 > n1+1 {
			c.strcet = strings.TrimSpace(s[n1+1 : n2])
			continue
		}

		if len(c.strcet) == 0 {
			continue
		}
		index := strings.Index(s,"=")
		if index < 0 {
			continue
		}

		frist := strings.TrimSpace(s[:index])
		if len(frist) == 0 {
			continue
		}
		second := strings.TrimSpace(s[index+1:])

		pos := strings.Index(second,"\t#")
		if pos > -1 {
			second = second[0:pos]
		}

		pos = strings.Index(second," #")
		if pos > -1 {
			second = second[0:pos]
		}

		pos = strings.Index(second,"\t//")
		if pos > -1 {
			second = second[0:pos]
		}

		pos = strings.Index(second," //")
		if pos > -1 {
			second = second[0:pos]
		}

		if len(second) == 0 {
			continue
		}

		key := c.strcet + middle + frist
		c.Mymap[key] = strings.TrimSpace(second)
	}
}

func (c Config) Read(node,key string) string {
	key = node + middle + key
	v,found := c.Mymap[key]
	if !found {
		return ""
	}
	return v
}

main.go


package main

import (
	"conf"
	"fmt"
)

func main() {
	myConfig := new(cf.Config)
	myConfig.InitConfig("c:/config.txt")
	fmt.Println(myConfig.Read("default","path"))
	fmt.Printf("%v",myConfig.Mymap)
}



result:
	c:/go
	map[default=========path:c:/go default=========version:1.44 test=========num:666 test=========something:wrong test=========refer:refer]

相关文章

程序目录结构 简单实现,用户登录后返回一个jwt的token,下次请求带上token请求用户信息接口并返回信息...
本篇博客的主要内容是用go写一个简单的Proof-of-Work共识机制,不涉及到网络通信环节,只是一个本地的简...
简介 默克尔树(MerkleTree)是一种典型的二叉树结构,其主要特点为: 最下面的叶节点包含存储数据或其...
接下来学习并发编程, 并发编程是go语言最有特色的地方, go对并发编程是原生支持. goroutine是go中最近本...
先普及一下, 什么是广度优先搜索 广度优先搜索类似于树的层次遍历。从图中的某一顶点出发,遍历每一个顶...
第一天: 接口的定义和实现 第二天: 一. go语言是面向接口编程. 在学习继承的时候说过, go语言只有封装,...