aconfig
aconfig copied to clipboard
Update example for cobra
Current version is outdated https://play.golang.org/p/OsCR8qTCN0H
Probably there will be another repository which will contains all the examples with external dependencies for https://github.com/cristalhq libraries, with a CI on cron
[update] The following example works, for a new playground link.
package main
import (
"os"
"github.com/cristalhq/aconfig"
"github.com/spf13/cobra"
)
type MyConfig struct {
User string `usage:"user of the app" default:"john"`
}
func main() {
var cfg MyConfig
loader := aconfig.LoaderFor(&cfg, aconfig.Config{})
args := struct {
logLevel string
}{}
cmd := &cobra.Command{
Use: "hello",
RunE: func(cmd *cobra.Command, _ []string) error {
if err := loader.Load(); err != nil {
return err
}
cmd.Printf("Hello World, %s!", cfg.User)
return nil
},
}
cmd.PersistentFlags().AddGoFlagSet(loader.Flags())
cmd.PersistentFlags().StringVar(&args.logLevel, "log-level", "info", "log level: debug, info, warning")
if err := cmd.Execute(); err != nil {
os.Exit(1)
}
}
Oh, great! Link: https://go.dev/play/p/zyXtrtL7NBu
Do you want to make a PR ? 😄 (if so, I have started adding GUIDE.md
file such things, see example https://github.com/cristalhq/acmd/blob/main/GUIDE.md + link to the guide in readme.md) and if no - I will add it a bit later.
Thank you once more.
I didn't make a PR because the thing I posted compiles and works, but outside the example it doesn't work super great having the configuration data and the command line arguments separated.
Can you clarify what is exactly not ok?
@cristaloleg I might be missing something, but with the cobra integration the configuration gets loaded into the aconfig "system", but the parameters get loaded into the cobra parameter system.
For my use case I'd like just the aconfig system and to ignore the cobra stuff except for integration in the help text, etc.