多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
## 编写一个 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 ~~~