viper


示例配置

# config.yaml
database:
  host: 127.0.0.1
  user: root
  pass: password
  port: 33060

使用viper读取配置

package main

import (
	"fmt"
	"os"

	"github.com/spf13/viper"
)

func main() {
	path, err := os.Getwd()
	if err != nil {
		panic(err)
	}

	config := viper.New()
	config.AddConfigPath(path)
	config.SetConfigName("config")
	config.SetConfigType("yaml")
	if err := config.ReadInConfig(); err != nil {
		panic(err)
	}

	fmt.Println(config.Get("database.host"))
	fmt.Println(config.Get("database.user"))
	fmt.Println(config.Get("database.pass"))
	fmt.Println(config.Get("database.port"))
}