Skip to content

Instantly share code, notes, and snippets.

@NonLogicalDev
Created January 26, 2021 00:11
Show Gist options
  • Select an option

  • Save NonLogicalDev/080082772b7b4c43ff375747908dd2c8 to your computer and use it in GitHub Desktop.

Select an option

Save NonLogicalDev/080082772b7b4c43ff375747908dd2c8 to your computer and use it in GitHub Desktop.
Go Cobra Environment Mapping Example
package main
import (
"context"
"fmt"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
var (
cmd = &cobra.Command{
Use: "goprompt",
RunE: cmdExecute,
}
)
func init() {
cmd.Flags().Int(
"cmd-status", 0, "cmd status of previous command",
)
cmd.Flags().Int(
"pre-exec-ts", 0, "pre-execution timestamp to gauge how log execution took",
)
cmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
return bindEnvironmentFlags(cmd, "prefix")
}
}
func bindEnvironmentFlags(cmd *cobra.Command, prefix string) error {
v := viper.New()
// Prep environment mapping.
v.SetEnvPrefix(prefix)
v.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
v.AutomaticEnv()
// Bind flagset and read in config.
if err := v.BindPFlags(cmd.Flags()); err != nil {
return err
}
if err := v.ReadInConfig(); err != nil {
return err
}
cmd.Flags().VisitAll(func(f *pflag.Flag) {
if !f.Changed && v.IsSet(f.Name) {
cmd.Flags().Set(f.Name, fmt.Sprintf("%v", v.Get(f.Name)))
}
})
return nil
}
func cmdExecute(cmd *cobra.Command, args []string) error {
return nil
}
func main() {
err := cmd.ExecuteContext(context.Background())
if err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment