【go】go类库-命令行工具cli

go类库:命令行工具cli

  • 1-引入库:go get github.com/urfave/cli

  • 2-code

// main.go
package main
import (
	"fmt"
	"os"
	"github.com/urfave/cli"
)
func main() {
	app := cli.NewApp()
	app.Commands = []cli.Command{
		{
			// 命令名称
			Name:  "test",
			Usage: "test --uid=x --username=y",
			// 通过Action 指定该命令执行方法
			Action: (&Command{}).Test,  
			Flags: []cli.Flag{
				cli.IntFlag{
					Name: "uid",
					Usage:"--uid",
				},
				cli.StringFlag{
					Name:"username",
					Usage:"--username",
				},
			},
		},
	}
	err := app.Run(os.Args)
	if err != nil {
		fmt.Print("command error :" + err.Error())
	}
}

// command.go
package main

import (
	"fmt"
	"github.com/urfave/cli"
)
type Command struct {
}

func (com *Command) Test(cli *cli.Context) {
	uid := cli.Int("uid")
	username := cli.String("username")
	fmt.Println(uid,username)
}

// 1-idea调试添加启动参数
PROGRAM ARGUMENTS:test --uid=111 --username="xiaoai"  // 结果:111 xiaoai

// 2-构建成二进制可执行文件启动  或者直接go build 打包成.exe可执行文件
go build -o test.bin  
test.bin test --uid=111 --username=xiaoai // 结果:111 xiaoai

版权声明:本文为qq_41617261原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
THE END
< <上一篇
下一篇>>