gin实例--viper基本用法

2,677 阅读1分钟

源码

github.com/zsl10/gin-e…

Viper功能

主要方便管理项目配置文件:

  • 支持读取JSON TOML YAML HCL 和Java属性配置文件
  • 监听配置文件变化,实时读取读取配置文件内容(可选)
  • 读取环境变量值
  • 读取远程配置系统(etcd Consul)和监控配置变化
  • 读取命令行Flag值
  • 读取buffer值
  • 提供一个配置文件默认值和可选值的机制

常用方法

如果配置项没有找到会获取的是零值:

  • Get(key string) : interface{}
  • GetBool(key string) : bool
  • GetFloat64(key string) : float64
  • GetInt(key string) : int
  • GetString(key string) : string
  • GetStringMap(key string) : map[string]interface{}
  • GetStringMapString(key string) : map[string]string
  • GetStringSlice(key string) : []string
  • GetTime(key string) : time.Time
  • GetDuration(key string) : time.Duration
  • 判断是否有这个配置项:IsSet(key string) : bool
  • AllSettings() : map[string]interface{}

读取配置顺序

  • Set
  • flag
  • env
  • config
  • key/value store
  • default

基本用法实例

package main

import (
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"log"
	"net/http"
)

func main() {
	viper.AddConfigPath("conf")   // 设置配置文件所在目录
	viper.SetConfigName("app") //设置配置文件名称
	viper.SetConfigType("yaml")   // 设置配置文件格式为YAML
	// viper解析配置文件
	if err := viper.ReadInConfig(); err != nil {
		log.Fatal(err)
	}
	runMode := viper.GetString("runmode")
	addr:=viper.GetString("addr")
	gin.SetMode(runMode) // 设置gin运行模式
	r := gin.Default()
	r.GET("test/config", func(c *gin.Context) {
		c.String(http.StatusOK,runMode)
	})
	r.Run(addr)
}