Fix config

This commit is contained in:
Daniel Ponte 2024-07-23 20:27:19 -04:00
parent 9f340799ac
commit 709cfceec4
2 changed files with 21 additions and 42 deletions

View file

@ -16,32 +16,19 @@ import (
func main() { func main() {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
rootCmd := cobra.Command{ rootCmd := &cobra.Command{
Use: gordio.AppName, Use: gordio.AppName,
} }
rootCmd.PersistentFlags().StringP("config", "c", "config.yaml", "config file") cfg := config.New(rootCmd)
rootCmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
err := rootCmd.ParseFlags(os.Args) return cfg.ReadConfig()
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")
} }
cmds := append([]*cobra.Command{gordio.Command(cfg)}, admin.Command(cfg)...) cmds := append([]*cobra.Command{gordio.Command(cfg)}, admin.Command(cfg)...)
rootCmd.AddCommand(cmds...) rootCmd.AddCommand(cmds...)
err = rootCmd.Execute() err := rootCmd.Execute()
if err != nil { if err != nil {
log.Fatal().Err(err).Msg("Dying") log.Fatal().Err(err).Msg("Dying")
} }
} }

View file

@ -1,8 +1,10 @@
package config package config
import ( import (
"gopkg.in/yaml.v3" "github.com/rs/zerolog/log"
"os" "os"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
) )
type Config struct { type Config struct {
@ -11,6 +13,8 @@ type Config struct {
Listen string `yaml:"listen"` Listen string `yaml:"listen"`
Public bool `yaml:"public"` Public bool `yaml:"public"`
Domain string `yaml:"domain"` Domain string `yaml:"domain"`
configPath string
} }
type DB struct { type DB struct {
@ -18,36 +22,24 @@ type DB struct {
Driver string `yaml:"driver"` Driver string `yaml:"driver"`
} }
type ConfigOption func(*configOptions) func New(cmd *cobra.Command) *Config {
c := &Config{}
type configOptions struct { cmd.PersistentFlags().StringVarP(&c.configPath, "config", "c", "config.yaml", "configuration file")
configPath string return c
} }
func WithConfigPath(p string) ConfigOption { func (c *Config) ReadConfig() error {
return func(o *configOptions) { cfgBytes, err := os.ReadFile(c.configPath)
o.configPath = p
}
}
func ReadConfig(opts ...ConfigOption) (*Config, error) {
o := new(configOptions)
for _, opt := range opts {
opt(o)
}
cfgBytes, err := os.ReadFile(o.configPath)
if err != nil { if err != nil {
return nil, err return err
} }
c := new(Config)
err = yaml.Unmarshal(cfgBytes, c) err = yaml.Unmarshal(cfgBytes, c)
if err != nil { if err != nil {
return nil, err return err
} }
return c, nil log.Info().Str("configPath", c.configPath).Msg("read gordio config")
return nil
} }