GoLang读取配置文件

log.ini(路径:$GOPATH/config/log.ini)

[run]
run_dir = /Users/why/Desktop/go/logs/run/
[error]
error_dir = /Users/why/Desktop/go/logs/error/

redis.ini(路径:$GOPATH/config/mysql.ini)

[why]
why_hostname = 127.0.0.1
why_port = 3306
why_db = 0
why_auth = why123

mysql.ini(路径:$GOPATH/config/redis.ini)

[why]
why_hostname = 127.0.0.1
why_username = why
why_password = why123
why_port = 3306
why_db = why
why_charset = utf8

config.go(路径:$GOPATH/src/why/config/.config.go)

需要go get "github.com/larspensjo/config"

package config

import (
	"flag"
	"fmt"
	"github.com/larspensjo/config"
	"gopkg.in/ini.v1"
	"runtime"
	"why/util"
)

type Config struct {
	Result	map[string]string
	Err		string
}

const path = "./config/"


func GetConfig(cfgType string, cfgSection string) *ini.Section{
	configFile := fmt.Sprintf("%s%s.ini", path, cfgType)

	cfgIni, err := ini.Load(configFile)
	util.Must(err)
	section := cfgIni.Section(cfgSection)

	return section
}

func (self *Config) getConfig(conn string, configFile string){
	runtime.GOMAXPROCS(runtime.NumCPU())
	flag.Parse()

	cfg, err := config.ReadDefault(configFile)   //读取配置文件,并返回其Config

	if err != nil {
		logMsg := fmt.Sprintf("Fail to find %v,%v", configFile, err)
		self.Err = logMsg
	}

	self.Result = map[string]string{}
	if	cfg.HasSection(conn) {   //判断配置文件中是否有section(一级标签)
		options, err := cfg.SectionOptions(conn)    //获取一级标签的所有子标签options(只有标签没有值)
		if err == nil {
			for _,v := range options{
				optionValue, err := cfg.String(conn, v)  //根据一级标签section和option获取对应的值
				if err == nil {
					self.Result[v] = optionValue
				}
			}
		}
	}
}

func GetConfigEntrance(cfgType string, cfgSection string) map[string]string {
	cfg := new(Config)
	cfg.getConfig(cfgSection, path + cfgType + ".ini")

	return cfg.Result
}

 

test.go

package main

import (
	"fmt"
	"log"
	"why/config"
)


func main(){
	runLogConfig := make(map[string]string)
	runLogSection := "run"
	runLogConfig = config.GetConfigEntrance("log", runLogSection)
	
        fmt.Println(runLogConfig)
}

 

https://ini.unknwon.io/docs/intro/getting_started

你可能感兴趣的:(go)