gotest/cmd/root.go
2019-09-24 22:23:20 -05:00

63 lines
1.2 KiB
Go

package cmd
import (
"fmt"
"os"
"github.com/kyoh86/xdg"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var cfgFile string
var rootCmd = &cobra.Command{
Use: "gotest",
Short: "Gotest is a thing for testing out go packaging and boilerplate",
Long: "An Experiment",
}
func init() {
cobra.OnInitialize(initConfig)
viper.SetDefault("addr", ":8000")
viper.SetDefault("env", "production")
rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c",
"", "Full path to config file")
}
func initConfig() {
viper.SetEnvPrefix("gotest")
viper.AutomaticEnv()
if cfgFile != "" {
viper.SetConfigFile(cfgFile)
} else {
for _, p := range xdg.AllConfigDirs() {
viper.AddConfigPath(p)
}
viper.SetConfigName("gotest")
}
viper.ReadInConfig()
if viper.GetString("env") == "production" {
log.SetFormatter(&log.JSONFormatter{})
log.SetOutput(os.Stdout)
} else {
log.SetFormatter(&log.JSONFormatter{
PrettyPrint: true,
FieldMap: log.FieldMap{
log.FieldKeyLevel: "priority",
log.FieldKeyTime: "timestamp",
log.FieldKeyMsg: "message",
},
DataKey: "opt"})
}
}
// Execute the root command
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}