So I have a cobra command created
func init() {
rootCmd.AddCommand(versionCmd)
}
var versionCmd = &cobra.Command{
Use: "version",
Short: "Show App version",
Long: "Show App version.",
Run: func(cmd *cobra.Command, args []string) {
dir, _ := os.Getwd()
db, err := gorm.Open(sqlite.Open(fmt.Sprintf("%s/db/db.sqlite", dir)), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
....
},
}
you can see the database connection code inside. Now I have to add the same Database connection code in all of the commands. Is there a way I can avoid this?
You can create a method to initialize db and use that inside the RUN arg. Try following:
Alternatively, if the
Run
function is gerenic for other commands as well, you can extract that function itself.