leighmcculloch/gochecknoglobals

How to avoid global variables using cobra?

Closed this issue · 2 comments

I'm using https://github.com/spf13/cobra and code like this:

  var cmdPrint = &cobra.Command{
    Use:   "print [string to print]",
    Short: "Print anything to the screen",
    Args: cobra.MinimumNArgs(1),
    Run: func(cmd *cobra.Command, args []string) {
      fmt.Println("Print: " + strings.Join(args, " "))
    },
  }
``

I get this error from golangci-lint:

cmdPrint is a global variable (gochecknoglobals)


Is there a way to satisfy the linter and to write a batter code?

Hi @frederikhors! Package level variables are almost always optional, you can move the cmdPrint variable into a function.

I use cobra in some projects and here are some examples of how to avoid globals when defining commands:
https://github.com/stellar/go/blob/772bcb2/exp/services/webauth/main.go#L14-L23
https://github.com/stellar/go/blob/772bcb2/exp/services/webauth/cmd/serve.go#L18