---
title: Cobra
---
# Cobra
###### tags: `Golang`
[Toc]
### 簡介
讓你的程式提供CLI指令工具的套件
### 簡易觀念
首先需要明确 3 个基本概念:
命令(Command):就是需要执行的操作;
参数(Arg):命令的参数,即要操作的对象;
选项(Flag):命令选项可以调整命令的行为。
下面示例中,server是一个(子)命令,--port是选项:
> hugo server --port=1313
下面示例中,clone是一个(子)命令,URL是参数,--bare是选项:
> git clone URL --bare
### 安裝
> go install github.com/spf13/cobra
ps.1: 如果報錯要你先go get 就照做,然後再go install就可以了
ps.2: 不要看網路上一堆三小要你go get 然後本地command not fund的雞巴教學
測試: cobra version
### Init
到專案目錄執行:
> cobra init
會自動在專案目錄第一層建立main.go, 並Execute 目錄cmd下的root.go
### 開始建立自己的command
在root同層建立其他的go服務,並在裡面向cobra註冊你要新增的subcommand
註冊方式看代碼: https://github.com/ronnielin8862/go-practice/blob/master/cmd/cobraTest.go
無法一次執行兩個subcommand
### 常用指令說明
```
var rootCmd = &cobra.Command{
Use: "serve",
Long: `A`,
Short: "B",
Run: func(cmd *cobra.Command, args []string) { fmt.Println("fuck") }
rootCmd.AddCommand(serveCmd) // 向rootCmd 註冊
matchLiveCmd.Flags().StringVarP(&cfgFile, "config", "c", "chatroom_config.toml", "config filename")
matchLiveCmd.Flags().BoolVarP(&printCfg, "print-config", "", false, "print config contents")
```
1. Use: 起專案時帶入的subcommand, 符合的時候便會進入以下的這坨屎
2. Short: 當你對專案執行help, or -h, 時會出現的提示,告訴user這subcommand可以幹三小蠢事。 ex: go run main.go -h (你會得到B)
3. Long: 當針對你的subcommand -h 時會出現的。 算是提示用戶的詳細訊息。 ex: go run main.go serve -h (你會得到A)
4. Run: 這才是重點,執行你要他幹的蠢事。 ex: go run main.go serve (你會得到 fuck)