【Go】手軽にCLIツールを作成できるCobraを触ってみた
更新日:2025/5/31/(土) 03:35
タグ:Go
概要
- Go製のCLIツールを簡単に開発できるフレームワークCobraを触ってみた
- インストール方法や簡単なサンプルコード
インストール、動作確認
- cobraをインストール
$ go get -u github.com/spf13/cobra@latest
- cobra-cliをインストール
$ go install github.com/spf13/cobra-cli@latest
- テンプレート作成
cobra-cli init --license MIT --viper=false
下記のようなテンプレートが作成される
├── cmd │ └── root.go ├── go.mod ├── go.sum ├── LICENSE ├── main.go
- 動作確認
$ go run main.go A longer description that spans multiple lines and likely contains examples and usage of using your application. For example:
コマンドを追加してみる
例えば「hello」というコマンドを作りたい場合は、
cobra-cli add hello
cmd/hello.go
が自動生成される
/* Copyright © 2025 NAME HERE <EMAIL ADDRESS> */ package cmd import ( "fmt" "github.com/spf13/cobra" ) // helloCmd represents the hello command var helloCmd = &cobra.Command{ Use: "hello", Short: "A brief description of your command", Long: `A longer description that spans multiple lines and likely contains examples and usage of using your command. For example: Cobra is a CLI library for Go that empowers applications. This application is a tool to generate the needed files to quickly create a Cobra application.`, Run: func(cmd *cobra.Command, args []string) { fmt.Println("hello called") }, } func init() { rootCmd.AddCommand(helloCmd) // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags which will work for this command // and all subcommands, e.g.: // helloCmd.PersistentFlags().String("foo", "", "A help for foo") // Cobra supports local flags which will only run when this command // is called directly, e.g.: // helloCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") }
実行してみる
$ go run main.go hello hello called
フラグの追加
package cmd import ( "fmt" "github.com/spf13/cobra" ) var name string // helloCmd represents the hello command var helloCmd = &cobra.Command{ Use: "hello", Short: "挨拶を表示するコマンド", Run: func(cmd *cobra.Command, args []string) { fmt.Printf("Hello, %s!\n", name) }, } func init() { rootCmd.AddCommand(helloCmd) // フラグ追加 helloCmd.Flags().StringVarP(&name, "name", "n", "World", "名前を指定できます") }
実行してみる
$ go run main.go hello # => Hello, World! $ go run main.go hello --name Taro # => Hello, Taro! $ go run main.go hello -n Jiro # => Hello, Jiro!
まとめ
- インストールから実行まで非常に手軽だった
- まだ作りたいCLI思い浮かばないが、機会があれば使っていきたい