diff --git a/cmd/api.go b/cmd/api.go index 1cd3f14..e9779d0 100644 --- a/cmd/api.go +++ b/cmd/api.go @@ -5,7 +5,9 @@ package cmd import ( "fmt" + "log" + "git.agecem.com/agecem/bottin-ag/config" "github.com/spf13/cobra" ) @@ -14,7 +16,13 @@ var apiCmd = &cobra.Command{ Use: "api", Short: "Start the API server", Run: func(cmd *cobra.Command, args []string) { - fmt.Println("api called") + cfg, err := config.GetConfig() + if err != nil { + log.Fatal(err) + } + + fmt.Println("api called with api-port", cfg.API.Port) + fmt.Println("api called with web-port", cfg.Web.Port) }, } diff --git a/cmd/root.go b/cmd/root.go index 3332c5c..d73c696 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -5,8 +5,10 @@ package cmd import ( "fmt" + "log" "os" + "git.agecem.com/agecem/bottin-ag/config" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -30,6 +32,10 @@ func init() { cobra.OnInitialize(initConfig) rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.bottin-ag.yaml)") + + if err := config.RegisterFlags(rootCmd); err != nil { + log.Fatal(err) + } } // initConfig reads in config file and ENV variables if set. diff --git a/config/config.go b/config/config.go index e69de29..e7698ea 100644 --- a/config/config.go +++ b/config/config.go @@ -0,0 +1,40 @@ +package config + +import ( + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +type Config struct { + API APIConfig + Web WebConfig +} + +type APIConfig struct { + Port int +} + +type WebConfig struct { + Port int +} + +func GetConfig() (cfg Config, err error) { + return cfg, viper.Unmarshal(&cfg) +} + +// RegisterFlags adds persistent flags necessary to the application to the specified *cobra.Command +func RegisterFlags(cmd *cobra.Command) error { + // api.port ; --api-port + cmd.PersistentFlags().Int("api-port", 3182, "API server port") + if err := viper.BindPFlag("api.port", cmd.PersistentFlags().Lookup("api-port")); err != nil { + return err + } + + // web.port ; --web-port + cmd.PersistentFlags().Int("web-port", 3183, "Webserver port") + if err := viper.BindPFlag("web.port", cmd.PersistentFlags().Lookup("web-port")); err != nil { + return err + } + + return nil +}