Skip to content

Instantly share code, notes, and snippets.

@JimFawkes
Last active August 18, 2023 09:55
Show Gist options
  • Save JimFawkes/cc4033da09f4264ab9fd36d5245cb50d to your computer and use it in GitHub Desktop.
Save JimFawkes/cc4033da09f4264ab9fd36d5245cb50d to your computer and use it in GitHub Desktop.
Example CLI, Env & Default Variables in Go using Viper and Cobra
// Example Usage of Viper & Cobra to parse CLI, Env & Default Vars.
//
// ------------------------------------------------------------
// $ FIRST=aaaa NUM=123 go run cli_env_example.go --first bbb
//
// Default: first=default-first, second=default-second, num=1
// Params: first=bbb, second=default-second, num=123
// ------------------------------------------------------------
// $ FIRST=aaaa NUM=123 go run cli_env_example.go --help
//
// My Sample CLI Application
//
// Usage:
// myapp [flags]
//
// Flags:
// -f, --first string First Param (default "aaaa")
// -h, --help help for myapp
// -n, --num int Num Param (default 123)
// -s, --second string Second Param (default "default-second")
// ------------------------------------------------------------
package main
import (
"fmt"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
type AppParams struct {
first string
second string
num int64
}
var AppDefaults = AppParams{
first: "default-first",
second: "default-second",
num: 1,
}
var params = AppParams{}
var rootCmd = &cobra.Command{
Use: "myapp",
Short: "My Sample CLI Application",
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("Default: first=%s, second=%s, num=%d\n", AppDefaults.first, AppDefaults.second, AppDefaults.num)
fmt.Printf("Params: first=%s, second=%s, num=%d\n", params.first, params.second, params.num)
// Do some important stuff ...
},
}
func init() {
viper.AutomaticEnv()
viper.SetDefault("first", AppDefaults.first)
viper.SetDefault("second", AppDefaults.second)
viper.SetDefault("num", AppDefaults.num)
rootCmd.PersistentFlags().StringVarP(&params.first, "first", "f", viper.GetString("first"), "First Param")
viper.BindPFlag("first", rootCmd.PersistentFlags().Lookup("first"))
rootCmd.PersistentFlags().StringVarP(&params.second, "second", "s", viper.GetString("second"), "Second Param")
viper.BindPFlag("second", rootCmd.PersistentFlags().Lookup("second"))
rootCmd.PersistentFlags().Int64VarP(&params.num, "num", "n", viper.GetInt64("num"), "Num Param")
viper.BindPFlag("num", rootCmd.PersistentFlags().Lookup("num"))
}
func main() {
if err := rootCmd.Execute(); err != nil {
fmt.Errorf("Encountered error: %v", err)
}
}
@JimFawkes
Copy link
Author

When going this route, consider rather the following:

Sting of the Viper - Post
Sting of the Viper - GitHub

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment