加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang 读取配置文件

发布时间:2020-12-16 18:51:30 所属栏目:大数据 来源:网络整理
导读:unix 风格的配置文件 [default]path= c:/goversion = 1.44 [test]num =666something = wrong #注释1#fdfdfd = fdfdfd 注释整行refer= refer //注释3 config.go package confimport ("bufio""io""os""strings")const middle = "========="type Config struct

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]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读