Meta-Viper is a wrapper over viper, it uses a Go tagged struct to:
-
Initialize viper's configuration.
-
Load application configuration on that same struct.
You can find examples at ./examples or in this article: https://carlosvin.github.io/posts/create-cmd-tool-golang.
Meta-Viper will try to load the configuration in that struct from configuration files, environment variables or flags.
package main
import (
"fmt"
"os"
config "github.com/carlosvin/meta-viper"
)
type appConfig struct {
Host string `cfg_name:"host" cfg_desc:"Server host"`
Port int `cfg_name:"port" cfg_desc:"Server port"`
SearchAPI string `cfg_name:"apis.search" cfg_desc:"Search API endpoint"`
}
func main() {
cfg := &appConfig{ // (1)
Host: "localhost",
Port: 6000,
SearchAPI: "https://google.es",
}
_, err := config.New(cfg, os.Args) // (2)
if err != nil {
panic(err)
}
log.Printf("Loaded Configuration %v...", cfg)
}
-
We instantiate the declared struct. As you can see you can optionally specify default values.
-
It loads the configuration in the passed struct
cfg
. Theos.Args
are required to parse the application flags.
Let’s focus on one application configuration attribute to explain the example. Meta-Viper will allow you to load the config into Host
structure attribute in 3 different ways:
./your-program --host=my.host
HOST=my.host ./your-program
./your-program --config=qa (1)
-
Following the qa configuration file content
{
"host": "qa.host",
"port": 8000,
"apis": {
"search": "https://search.api/"
}
}
Note
|
You can combine flags, environment variables and configuration files. |