## 編寫一個 Console 命令行
首先我們使用 `mix` 命令創建一個 Console 項目骨架:
~~~
mix new --name=hello
~~~
我們打開 `main.go` 文件能發現該骨架程序使用 `github.com/mix-go/console` 開發,`console.NewApplication` 傳入了一個配置信息,這個配置信息定義了該程序內部包含的命令配置和程序需要使用的 DI、IoC 容器依賴配置,這兩個是 Console 最核心的兩個配置。
- DI、IoC 容器依賴配置信息:manifest/beans
- 命令配置信息:manifest/commands
然后我們在 `commands` 新建 `commands/hello.go` 文件:
- 定義一個新的命令結構體 `HelloCommand`
- `HelloCommand.Main` 方法為默認執行的入口方法
- 代碼中獲取了兩個命令行參數,并將參數打印到屏幕
~~~
package commands
import (
"fmt"
"github.com/mix-go/console/flag"
)
type HelloCommand struct {
}
func (t *HelloCommand) Main() {
name := flag.Match("n", "name").String("Xiao Ming")
say := flag.Match("say").String("Hello, World!")
fmt.Printf("%s: %s\n", name, say)
}
~~~
然后我們把上面的 `HelloCommand` 在 `manifest/commands` 中注冊,新增一個命令配置:
- 新建 `manifest/commands/hello.go` 文件
- 代碼中采用 init 方法在程序初始化的時候自動執行,將一個新的 hello 命令追加到 Commands 全局變量中,最后傳遞到 `console.NewApplication` 中執行。
- CommandDefinition 中的字段信息都會在 `./go_build_main_go --help` 或者 `./go_build_main_go hello --help` 中以固定的格式呈現,自動完成一個帶參數的命令行程序。
- Command 字段定義了 hello 命令將調用的結構體,通過這個功能我們就可以編寫具有多個子功能的完整命令行程序。
- 注意:所有在程序中需要使用 flag.Match(***) 獲取參數值的選項都必須在 Options 字段中定義。
~~~
package commands
import (
"github.com/mix-go/console"
"github.com/mix-go/mix-console-skeleton/commands"
)
func init() {
Commands = append(Commands,
console.CommandDefinition{
Name: "hello",
Usage: "\tEcho demo",
Options: []console.OptionDefinition{
{
Names: []string{"n", "name"},
Usage: "Your name",
},
{
Names: []string{"say"},
Usage: "\tSay ...",
},
},
Command: &commands.HelloCommand{},
},
)
}
~~~
## 編譯與測試
> 也可以在 Goland Run 里配置 Program arguments 直接編譯執行,[Goland 使用] 章節有詳細介紹
接下來我們編譯上面的程序:
~~~
// linux & macOS
go build -o bin/go_build_main_go main.go
// win
go build -o bin/go_build_main_go.exe main.go
~~~
查看全部命令的幫助信息:
~~~
$ cd bin
$ ./go_build_main_go
Usage: ./go_build_main_go [OPTIONS] COMMAND [opt...]
Global Options:
-h, --help Print usage
-v, --version Print version information
Commands:
db Database query demo
hello Echo demo
wp Worker pool demo
wpd Worker pool daemon demo
Run './go_build_main_go COMMAND --help' for more information on a command.
Developed with Mix Go framework. (openmix.org/mix-go)
~~~
查看上面編寫的 hello 命令的幫助信息:
~~~
$ ./go_build_main_go hello --help
Usage: ./go_build_main_go hello [opt...]
Command Options:
-n, --name Your name
--say Say ...
Developed with Mix Go framework. (openmix.org/mix-go)
~~~
執行 `hello` 命令,并傳入兩個參數:
~~~
$ ./go_build_main_go hello --name=liujian --say=hello
liujian: hello
~~~