Viper —— configuration solution for Go

发布时间 2023-11-03 20:48:59作者: PEAR2020

1. support several formats of configuration

config.yaml

name: 'bobby'
port: 12334

main.go to quick start 

package main

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

type ServerConfig struct { 
    ServiceName string `mapstructure:"name"`    // using mapstructure to support other forms of config & using mapstructure pkg
    Port        int    `mapstructure:"port"`
}

func main() {
    v := viper.New() // return a Viper
    v.SetConfigFile("viper_test/ch01/config.yaml")
    //v.SetConfigFile("config.yaml")
    if err := v.ReadInConfig(); err != nil {
        panic(err)
    }
    sc := ServerConfig{}
    if err := v.Unmarshal(&sc); err != nil {  // unserilaize to Object
        panic(err)
    }
    fmt.Println(sc)
    fmt.Println(v.Get("name"))
}