GoでCLIを作る

GolangCLIを作成する。

前準備

作業用のディレクトリと、必要なモジュールをインストールする

# 作業用ディレクトリ作成およびモジュール作成
$ 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()
}

単純に、cmdExecute()を実行しているだけであることがわかる。

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 言語入門

参考

【Golang】1日でGoのcobraでサクッとCLIが作れちゃった話