Merge branch 'feature/config-ports' into 'main'
Ajouter et implémenter bases de config cobra/viper dans config/
This commit is contained in:
commit
09e2a155e4
3 changed files with 55 additions and 1 deletions
10
cmd/api.go
10
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)
|
||||
},
|
||||
}
|
||||
|
||||
|
|
|
@ -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.
|
||||
|
|
|
@ -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
|
||||
}
|
Loading…
Reference in a new issue