对于配置文件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.modedevelopment
使用
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