github.com/dhax/go-base@v0.0.0-20231004214136-8be7e5c1972b/cmd/root.go (about)

     1  package cmd
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"os"
     7  
     8  	homedir "github.com/mitchellh/go-homedir"
     9  	"github.com/spf13/cobra"
    10  	"github.com/spf13/viper"
    11  )
    12  
    13  var cfgFile string
    14  
    15  // RootCmd represents the base command when called without any subcommands
    16  var RootCmd = &cobra.Command{
    17  	Use:   "go-base",
    18  	Short: "A RESTful API boilerplate",
    19  	Long:  `A RESTful API boilerplate with passwordless authentication.`,
    20  	// Uncomment the following line if your bare application
    21  	// has an action associated with it:
    22  	//	Run: func(cmd *cobra.Command, args []string) { },
    23  }
    24  
    25  // Execute adds all child commands to the root command and sets flags appropriately.
    26  // This is called by main.main(). It only needs to happen once to the rootCmd.
    27  func Execute() {
    28  	if err := RootCmd.Execute(); err != nil {
    29  		fmt.Println(err)
    30  		os.Exit(1)
    31  	}
    32  }
    33  
    34  func init() {
    35  	cobra.OnInitialize(initConfig)
    36  
    37  	// Here you will define your flags and configuration settings.
    38  	// Cobra supports persistent flags, which, if defined here,
    39  	// will be global for your application.
    40  	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.go-base.yaml)")
    41  	RootCmd.PersistentFlags().Bool("db_debug", false, "log sql to console")
    42  	viper.BindPFlag("db_debug", RootCmd.PersistentFlags().Lookup("db_debug"))
    43  
    44  	// Cobra also supports local flags, which will only run
    45  	// when this action is called directly.
    46  	// RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
    47  }
    48  
    49  // initConfig reads in config file and ENV variables if set.
    50  func initConfig() {
    51  	if cfgFile != "" {
    52  		// Use config file from the flag.
    53  		viper.SetConfigFile(cfgFile)
    54  	} else {
    55  		// Find home directory.
    56  		home, err := homedir.Dir()
    57  		if err != nil {
    58  			log.Fatal(err)
    59  		}
    60  
    61  		// Search config in home directory with name ".go-base" (without extension).
    62  		viper.AddConfigPath(home)
    63  		viper.SetConfigName(".go-base")
    64  	}
    65  
    66  	viper.AutomaticEnv() // read in environment variables that match
    67  
    68  	// If a config file is found, read it in.
    69  	if err := viper.ReadInConfig(); err == nil {
    70  		fmt.Println("Using config file:", viper.ConfigFileUsed())
    71  	}
    72  }