majianyu
11/22/2018 - 12:55 PM

viper_config

// Author: Mjy
// Create Date: 2018-11-23
package config

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"strings"
)

type ApiConfig struct {
	RunMode      string `mapstructure:"runmode"`
	Addr         string `mapstructure:"addr"`
	Port         int    `mapstructure:"port"`
	Name         string `mapstructure:"name"`
	Url          string `mapstructure:"url"`
	MaxPingCount int    `mapstructure:"max_ping_count"`
}

var Config = &ApiConfig{}

func InitConfig(cfg string) error {
	c := viper.New()
	if err := initConfig(cfg, c); err != nil {
		return err
	}
	if err := c.UnmarshalExact(Config); err != nil {
		return err
	}
	c.WatchConfig()
	c.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("Config file changed:" + e.Name)
		c.Unmarshal(Config)
	})
	return nil
}

func initConfig(cfg string, c *viper.Viper) error {
	c.SetConfigType("yaml")
	if cfg == "" {
		c.SetConfigFile("/Users/majianyu/Code/go/GoLandProjects/dsers/src/api/conf/config.yaml")
	} else {
		c.SetConfigFile(cfg)
	}
	c.AutomaticEnv()
	c.SetEnvPrefix("APISERVER")
	replacer := strings.NewReplacer(".", "_")
	c.SetEnvKeyReplacer(replacer)

	if err := c.ReadInConfig(); err != nil {
		return err
	}
	return nil
}
runmode: debug
addr: 127.0.0.1
port: 8080
name: api
url: http://127.0.0.1:8080
max_ping_count: 10
// Author: Mjy
// Create Date: 2018-11-23
package main

import (
	"api/config"
	"github.com/spf13/pflag"
)

var cfg = pflag.StringP("config", "c", "", "apiserver config file path.")

func main() {
	pflag.Parse()
	if err := config.InitConfig(*cfg); err != nil {
		panic(err)
	}
}