|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + |
| 7 | + "github.com/spf13/cobra" |
| 8 | + |
| 9 | + homedir "github.com/mitchellh/go-homedir" |
| 10 | + "github.com/spf13/viper" |
| 11 | + |
| 12 | + c "github.com/bmaynard/apimock/pkg/cmd" |
| 13 | + "github.com/bmaynard/apimock/pkg/config" |
| 14 | + l "github.com/bmaynard/apimock/pkg/utils/logger" |
| 15 | +) |
| 16 | + |
| 17 | +var ( |
| 18 | + cfgFile string |
| 19 | +) |
| 20 | + |
| 21 | +func NewApiMockApp() *cobra.Command { |
| 22 | + cobra.OnInitialize(initConfig) |
| 23 | + |
| 24 | + var rootCmd = &cobra.Command{ |
| 25 | + Use: "apimock", |
| 26 | + Short: "API Mock server", |
| 27 | + Long: `Run an API Mock server as well as the ability to record real requests to mock later`, |
| 28 | + } |
| 29 | + |
| 30 | + rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.apimock.yaml)") |
| 31 | + rootCmd.AddCommand(c.NewCmdProxyServer()) |
| 32 | + rootCmd.AddCommand(c.NewCmdMockServer()) |
| 33 | + |
| 34 | + return rootCmd |
| 35 | +} |
| 36 | + |
| 37 | +// initConfig reads in config file and ENV variables if set. |
| 38 | +func initConfig() { |
| 39 | + if cfgFile != "" { |
| 40 | + // Use config file from the flag. |
| 41 | + viper.SetConfigFile(cfgFile) |
| 42 | + } else { |
| 43 | + // Find home directory. |
| 44 | + home, err := homedir.Dir() |
| 45 | + if err != nil { |
| 46 | + fmt.Println(err) |
| 47 | + os.Exit(1) |
| 48 | + } |
| 49 | + |
| 50 | + // Search config in home directory with name ".apimock" (without extension). |
| 51 | + viper.AddConfigPath(home) |
| 52 | + viper.SetConfigName(".apimock") |
| 53 | + } |
| 54 | + |
| 55 | + viper.AutomaticEnv() // read in environment variables that match |
| 56 | + |
| 57 | + // If a config file is found, read it in. |
| 58 | + if err := viper.ReadInConfig(); err == nil { |
| 59 | + fmt.Println("Using config file:", viper.ConfigFileUsed()) |
| 60 | + } |
| 61 | + |
| 62 | + err := viper.Unmarshal(&config.Configuration) |
| 63 | + |
| 64 | + if err != nil { |
| 65 | + l.Log.Errorf("unable to decode into struct, %v", err) |
| 66 | + } |
| 67 | +} |
0 commit comments