how to have each cobra command parse its own flags? getting initialization loop (expected, but how to avoid?)

2.6k Views Asked by At

I'm following the guide on https://github.com/spf13/cobra#flags, but I'm confused by some of the content there.

I have a few services (rest api, email service, events) and I'm trying to do something like this:

go run *.go rest -env DEV -p 3000

go run *.go events -env DEV -p 3001

I'm following the github page, so I have defined my rootCmd and restCmd as such:

var rootCmd = &cobra.Command{
    Use: "myappname",
}

var restCmd = &cobra.Command{
    Use:   "rest",
    Short: "REST API",
    Long:  "REST API",
    Run:   runRest,
}

And in the runRest method, should I be doing something like

var env string
restCmd.Flags().StringVarP(&env, "env", "env", "", "environment")

Please let me know.

Thanks

1

There are 1 best solutions below

1
On BEST ANSWER

Each sub command can have their own flags. You can do this as following:

package main

import (
    "fmt"
    "log"

    "github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
    Use: "app",
}

func NewCmdRest() *cobra.Command {
    var env string
    var restCmd = &cobra.Command{
        Use: "rest",
        Run: func(cmd *cobra.Command, args []string) {
            fmt.Println("rest:", env)
        },
    }

    restCmd.Flags().StringVarP(&env, "env", "e", "", "environment")
    return restCmd
}

func NewCmdEvent() *cobra.Command {
    var env string
    var eventCmd = &cobra.Command{
        Use: "event",
        Run: func(cmd *cobra.Command, args []string) {
            fmt.Println("event:", env)
        },
    }

    eventCmd.Flags().StringVarP(&env, "env", "e", "", "environment")
    return eventCmd
}

func init() {
    rootCmd.AddCommand(NewCmdRest())
    rootCmd.AddCommand(NewCmdEvent())
}

func main() {
    if err := rootCmd.Execute(); err != nil {
        log.Fatal(err)
    }
}