Why use Viper
You can read configuration information from configuration files, environment variables, command line parameters, remote configurations such as ETCD, and listen for configuration updates, similar to the front-end build reading node environment variables or env files
code
port: 8123
version: "v1.2.6"
Copy the code
package main
import (
"fmt"
"net/http"
"github.com/fsnotify/fsnotify"
"github.com/gin-gonic/gin"
"github.com/spf13/viper"
)
type Config struct {
Port int `mapstructure:"port"`
Version string `mapstructure:"version"`
}
var Conf = new(Config)
func main(a) {
viper.SetConfigFile("./conf/config.yaml") // Specify the configuration file path
err := viper.ReadInConfig() // Read the configuration information
iferr ! =nil { // Failed to read configuration information
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
// Save the read configuration information to the global variable Conf
iferr := viper.Unmarshal(Conf); err ! =nil {
panic(fmt.Errorf("unmarshal conf failed, err:%s \n", err))
}
// Monitor configuration file changes
viper.WatchConfig()
// Attention!! Changes to the configuration file must be synchronized to the global Conf variable
viper.OnConfigChange(func(in fsnotify.Event) {
fmt.Println("The configuration file has been modified...")
iferr := viper.Unmarshal(Conf); err ! =nil {
panic(fmt.Errorf("unmarshal conf failed, err:%s \n", err))
}
})
r := gin.Default()
// The return value for accessing /version changes as the configuration file changes
r.GET("/version".func(c *gin.Context) {
c.String(http.StatusOK, Conf.Version)
})
if err := r.Run(fmt.Sprintf(":%d", Conf.Port)); err ! =nil {
panic(err)
}
}
Copy the code
Request interface
Modify the configuration