golang 读取配置文件信息(toml格式配置文件)

Golang · Fecmall · 于 5年前 发布 · 7289 次阅读

库包地址: https://github.com/spf13/viper

对于配置文件config.toml,格式如下:

[server]
mode = "development"
port = 8080
debug = true
http_timeout = 20000
jwt_timeout = 8640000
log_path = "./log/tix-log.log"
maps = "./map_data.json"
order_timeout = 600

[development]
baseURL = "http://dev.xxxxx.com:2121/partner-service/"
clientID = "xxxx"
schedule_expired_before = 900
promo_activity_id = "ttttttt"

[production]
baseURL = "http://prod.xxxxx.com:2121/partner-service/"
clientID = "yyyy"
schedule_expired_before = 900
promo_activity_id = "kkkkkkkkkk"

通过 server.mode 的方式读取 环境配置值,也就是 development, 然后 development.baseURL读取到开发环境的值

使用

package main

import (
	"flag"
	"fmt"
	"os"
	"xxxxx/config"
	
)


func main() {

	configFile := flag.String("c", "", "Configuration File")
	flag.Parse()
	if *configFile == "" {
		fmt.Println("\n\nUse -h to get more information on command line options\n")
		fmt.Println("You must specify a configuration file")
		os.Exit(1)
	}
	
	err := config.Initialize(*configFile)
	if err != nil {
		fmt.Printf("Error reading configuration: %s\n", err.Error())
		os.Exit(1)
	}
	// 打印配置值
	
	fmt.Println(config.MustGetString("server.maps"))
	
	mode := config.MustGetString("server.mode")
	
	
	baseURL := config.MustGetString(mode + ".mode")
	

"xxxxx/config"包

package config

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"github.com/spf13/viper"
)

func Initialize(fileName string) error {
	splits := strings.Split(filepath.Base(fileName), ".")
	viper.SetConfigName(filepath.Base(splits[0]))
	viper.AddConfigPath(filepath.Dir(fileName))
	err := viper.ReadInConfig()
	if err != nil {
		return err
	}
	return nil
}

func checkKey(key string) {
	if !viper.IsSet(key) {
		fmt.Printf("Configuration key %s not found; aborting \n", key)
		os.Exit(1)
	}
}

func MustGetString(key string) string {
	checkKey(key)
	return viper.GetString(key)
}

func MustGetInt(key string) int {
	checkKey(key)
	return viper.GetInt(key)
}

func MustGetBool(key string) bool {
	checkKey(key)
	return viper.GetBool(key)
}

func GetString(key string) string {
	return viper.GetString(key)
}

go run main.go -c config.toml 即可读取配置文件里面的内容

共收到 0 条回复
没有找到数据。
添加回复 (需要登录)
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册
Your Site Analytics