1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

golang cobra実装方法

Last updated at Posted at 2020-04-30

golang、cobraの実装について検索すると自動生成でなんとかなってしまうし
自動生成に関する記事もそれぞれ若干方法が違うからそもそもの書き方をメモ。

main.go
func main() {
	if err := cmd.NewCommand().Execute(); err != nil {
		fmt.Println(err)
	}
}
cmd/cmd.go
func NewCommand() *cobra.Command {

	cmd := &cobra.Command{
		Use:   "コマンド名",
		Short: "説明",
		RunE: func(c *cobra.Command, args []string) error {
			//実装
			return nil
		},
	}
//サブコマンドを追加したらここに追加
	cmd.AddCommand(SubCmd())
	return cmd
}

cmd/subcmd.go

type Option struct {
   sampleOption string
}

func SubCmd() *cobra.Command {
    o := &Option{}
	subCmd := &cobra.Command{
		Use:   "サブコマンド名",
		Short: "説明",
		RunE: func(cmd *cobra.Command, args []string) error {
			//実装
				return nil
			}
		},
	}
        
       //opiton
	SubCmd.Flags().StringVar(&o.sampleOption, "p", "sample", "sample")
	
	return SubCmd
}

自動生成だと各コマンドが変数になってしまうので、
関数になるこっちのが良いと思います。
上記コピペでコマンド量産可能。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?