Viper 的傳統用法局部,加載到某個 package 下的全局變量后,其它 package 可以繼續使用。
var Conf *viper.Viper func init() { // File name without extension '.json' filenameWithoutExt := "app.env" Conf.SetConfigName(filenameWithoutExt) Conf.SetConfigType("json") Conf.AddConfigPath("./setting") if err := Conf.ReadInConfig(); err != nil { panic("Using config file:" + Conf.ConfigFileUsed()) } }
要打包文件到二進制中,推薦的工具是 go-bindata/go-bindata
通過命令 `go-bindata -o bindata.go setting/` 在當前目錄生成 go 文件,里面有一個 Assert() 函數,main.go 中可以使用。
然后在 main.go 中通過 Viper io 讀取的方式讀取 Assert() 返回的 []bytes,代碼局部如下:
filename := "setting/app.env.json" bytesContent, err := Asset(filename) if err != nil { panic("Asset() can not found setting file") } Conf.SetConfigType("json") Conf.ReadConfig(bytes.NewBuffer(bytesContent))
Config *viper.Viper 的值可以設置到其它模塊中,方便在外部使用。
通過以上操作,我們可以在任何地方運行 build 生成的二進制文件了。