GoLang 프로필 읽기

2299 단어 go
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

좋은 웹페이지 즐겨찾기