1

I have written a cli tool for use within my org, to make connecting to certain DB's easier.

Not sure how to word this question, so an example will hopefully explain. I would like to use a config like so:

databases:
    db1: db1.endpoint.company.org
    db2: db2.endpoint.company.org

Then run the command like so:

toolbox db connect -host db1

I am not sure what the wording is of what I am asking so I haven't been able to search effectively for it. Even just some docs would be helpful.

fraserc182
  • 237
  • 1
  • 4
  • 13

1 Answers1

0

If I understand your question correctly you can use the following packages to achieve it:

  • cobra, for the cli commands structure and flags handling. (you can use cobra-cli to dive in faster)
  • viper, for the config deserializing.

Run cobra-cli --viper and edit the root command (or which command you want to implement it in) like so:

var rootCmd = &cobra.Command{
    Use: "toolbox",
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Println(
            viper.Get(
                fmt.Sprintf(
                    "databases.%s",
                    cmd.Flag("host").Value.String())))
    },
}

you need also to add the host flag:

func init() {
    cobra.OnInitialize(initConfig)
    
    rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.play.yaml)")
    rootCmd.Flags().String("host", "db1", "")
}
joel
  • 11
  • 4