The traditional usage of Viper is local. After loading into a global variable under a package, other packages can continue to be used.
var Conf *viper.Viper func init() { // File name without extension '.json' filenameWithoutExt := "env.debug" Conf.SetConfigName(filenameWithoutExt) Conf.SetConfigType("json") Conf.AddConfigPath("./setting") // Project dir if err := Conf.ReadInConfig(); err != nil { panic("Using config file:" + Conf.ConfigFileUsed()) } }
To package files into binary, the recommended tool is go-bindata / go-bindata
Use the command `go-bindata -o bindata.go setting /` to generate a go file in the current directory, which has an Assert () function, which can be used in main.go.
Then read the [] bytes returned by Assert () in main.go via Viper io. The code is as follows:
filename := "setting/env.debug.json" bytesContent, err := Asset(filename) if err != nil { panic("Asset() can not found setting file") } Conf.SetConfigType("json") Conf.ReadConfig(bytes.NewBuffer(bytesContent))
The value of Config * viper.Viper can be set to other modules to facilitate external use.
Through the above operations, we can run the binary file generated by the build anywhere.