From 709cfceec4bb32810ec4c3f8c0757ef837d80231 Mon Sep 17 00:00:00 2001 From: Daniel Ponte Date: Tue, 23 Jul 2024 20:27:19 -0400 Subject: [PATCH] Fix config --- cmd/gordio/main.go | 23 +++++---------------- pkg/gordio/config/config.go | 40 +++++++++++++++---------------------- 2 files changed, 21 insertions(+), 42 deletions(-) diff --git a/cmd/gordio/main.go b/cmd/gordio/main.go index d0ea913..7521331 100644 --- a/cmd/gordio/main.go +++ b/cmd/gordio/main.go @@ -16,32 +16,19 @@ import ( func main() { log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) - rootCmd := cobra.Command{ + rootCmd := &cobra.Command{ Use: gordio.AppName, } - rootCmd.PersistentFlags().StringP("config", "c", "config.yaml", "config file") - - err := rootCmd.ParseFlags(os.Args) - if err != nil { - log.Fatal().Err(err).Msg("parsing flags") - } - - cfgPath, err := rootCmd.PersistentFlags().GetString("config") - if err != nil { - log.Fatal().Err(err).Msg("failed parsing config path") - } - - cfg, err := config.ReadConfig(config.WithConfigPath(cfgPath)) - if err != nil { - log.Fatal().Err(err).Msg("Config read failed") + cfg := config.New(rootCmd) + rootCmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error { + return cfg.ReadConfig() } cmds := append([]*cobra.Command{gordio.Command(cfg)}, admin.Command(cfg)...) rootCmd.AddCommand(cmds...) - err = rootCmd.Execute() + err := rootCmd.Execute() if err != nil { log.Fatal().Err(err).Msg("Dying") } - } diff --git a/pkg/gordio/config/config.go b/pkg/gordio/config/config.go index a624c50..de865d2 100644 --- a/pkg/gordio/config/config.go +++ b/pkg/gordio/config/config.go @@ -1,8 +1,10 @@ package config import ( - "gopkg.in/yaml.v3" + "github.com/rs/zerolog/log" "os" + "github.com/spf13/cobra" + "gopkg.in/yaml.v3" ) type Config struct { @@ -11,6 +13,8 @@ type Config struct { Listen string `yaml:"listen"` Public bool `yaml:"public"` Domain string `yaml:"domain"` + + configPath string } type DB struct { @@ -18,36 +22,24 @@ type DB struct { Driver string `yaml:"driver"` } -type ConfigOption func(*configOptions) - -type configOptions struct { - configPath string +func New(cmd *cobra.Command) *Config { + c := &Config{} + cmd.PersistentFlags().StringVarP(&c.configPath, "config", "c", "config.yaml", "configuration file") + return c } -func WithConfigPath(p string) ConfigOption { - return func(o *configOptions) { - o.configPath = p - } -} - -func ReadConfig(opts ...ConfigOption) (*Config, error) { - o := new(configOptions) - - for _, opt := range opts { - opt(o) - } - - cfgBytes, err := os.ReadFile(o.configPath) +func (c *Config) ReadConfig() error { + cfgBytes, err := os.ReadFile(c.configPath) if err != nil { - return nil, err + return err } - c := new(Config) - err = yaml.Unmarshal(cfgBytes, c) if err != nil { - return nil, err + return err } - return c, nil + log.Info().Str("configPath", c.configPath).Msg("read gordio config") + + return nil }