CLI with viper config

Build a Go CLI by combining Cobra for command parsing with Viper for flexible configuration management.

Use Cobra for command parsing and Viper for configuration management to build a robust CLI.

package main

import (
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var rootCmd = &cobra.Command{
	Use:   "myapp",
	Short: "A brief description of your application",
	Run: func(cmd *cobra.Command, args []string) {
		// Access config via viper.Get("key")
	},
}

func init() {
	viper.SetConfigFile("config.yaml")
	viper.AutomaticEnv()
	if err := viper.ReadInConfig(); err == nil {
		// Config loaded
	}
	rootCmd.PersistentFlags().String("config", "", "config file path")
	_ = viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config"))
}

func main() {
	if err := rootCmd.Execute(); err != nil {
		// Handle error
	}
}