GoにおけるCLIの勉強
GoにおけるCLIの勉強
今回は,GoにおいてのCLIの基本的な事項のまとめと練習を行った.
cobraライブラリの導入
CLIを作る上で必須とも言えるライブラリが「cobra」というものらしい. いろいろ賢い処理を自動でやってくれてとても助かるらしいので,とりあえずgithubから取ってくる.
早速ライブラリのドキュメントを見てみよう.
できることをまとめると以下のような感じ.
サブコマンドを容易に追加
コマンドフラグ,インテリジェンス,ヘルプ等の機能提供
etc...
みようみまねでコマンドラインを一つ作成してみた. 構成は以下の通り
mycommand ├── cmd │ └── cmd.go └── main.go
メイン実行ファイル
package main import ( "log" "./cmd" ) func main() { err := cmd.RootCmd.Execute() if err != nil { log.Fatal(err) } }
コマンドを記述したファイル
package cmd import ( "fmt" "log" "strconv" "github.com/spf13/cobra" ) func init() { cobra.OnInitialize() RootCmd.AddCommand(SumCmd()) } var RootCmd = &cobra.Command{ // 関数名 Use: "mycmd", // 「ヘルプ」出力に表示される短い説明 Short: "very simple command", // 'help <this-command>'出力に表示される長いメッセージ Long: `This command is made for learning how to make commands with cobra.`, // 実行用の関数 Run: func(cmd *cobra.Command, args []string) { fmt.Printf("command [%s] has called!\n", cmd.Use) }, } func SumCmd() *cobra.Command { cmd := &cobra.Command{ Use: "sum", Short: "sum calc", Long: `this command calculate the summations of all argument params. `, RunE: func(cmd *cobra.Command, args []string) error { if len(args) == 0 { return nil } var ans int for _, arg := range args { item, err := strconv.Atoi(arg) if err != nil { log.Fatal(err) return err } ans += item } fmt.Printf("summation : %d\n", ans) return nil }, } return cmd }
ビルドして得られた実行ファイルに対して出力を確認してみよう.
$./mycommand sum 1 2 3 4 5 summation : 15 $./mycommand sum $./mycommand sum 1 summation : 1 $./mycommand undefined Error: unknown command "undefined" for "mycmd" Run 'mycmd --help' for usage. 2022/04/07 22:34:06 unknown command "undefined" for "mycmd" $./mycommand sum 1.0 2 3 2022/04/07 22:35:43 strconv.Atoi: parsing "1.0": invalid syntax
とりあえずは基本的な部分は良さそう?
****感想
cobra便利ですね.
相変わらず知らんことばっかりなので大変です.