Golang
でCLIを作成する。
前準備
作業用のディレクトリと、必要なモジュールをインストールする
# 作業用ディレクトリ作成およびモジュール作成 $ mkdir myapp $ cd myapp $ go mod init github.com/{USER_NAME}/myapp # CLIを作成するに便利なパッケージ群を取得する $ go install github.com/spf13/cobra-cli@latest $ go get -u github.com/spf13/cobra@latest
テンプレートの作成
以下のコマンドを実行する
$ cobra-cli init --license MIT --viper=false # 以下のような表示が出ればOK Your Cobra application is ready at <APP_DIRECTORY>
上記のコマンドが成功すると、ディレクトリにアプリケーションの雛形が作成された状態となる。以下はtree
コマンドの結果。
% tree . ├── LICENSE ├── cmd │ └── root.go ├── go.mod ├── go.sum └── main.go
main.go
の中身を見てみる。
package main import "github.com/sho03/make_json_go/cmd" func main() { cmd.Execute() }
単純に、cmd
のExecute()
を実行しているだけであることがわかる。
cobra.Command
肝になるのは、cmdディレクトリ配下のroot.go
になる。
そのうち、rootCmd
を定義している部分の、cobra.Command
構造体のRun
に渡す関数がメインの処理になる。
以下は、自動生成されたコードを少し編集して実行するとHello, world!
をプロンプトに表示するようにしたもの。
var rootCmd = &cobra.Command{ Use: "make_json_go", Short: "A brief description of your application", Long: `A longer description that spans multiple lines and likely contains examples and usage of using your application. 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.`, // Uncomment the following line if your bare application // has an action associated with it: Run: func(cmd *cobra.Command, args []string) { fmt.Println("Hello, world!") }, }
Run
に定義する関数をいじれば諸々自分のしたいことができるはず。今回はここまで。
おまけ)つまづいたところ
cobra-cli init
を実行したところ、コマンドが存在しないエラーが発生した。GOPATH
が通っていなかったことが原因なので、PATHに追加すればOK。
# goの環境変数を確認する $ go env GOPATH
あとは上記の結果を.zshrc
などに追記すればよい。
参考)
Go の GOPATH 環境変数 - Goの開発環境 - Go 言語入門