Golang中基础的命令行模块urfave/cli的用法说明

详细信息参考:https://www.jb51.net/article/202380.htm

package main 
import (
 "github.com/urfave/cli"
 "os"
 "log"
 "fmt"
)
  
func main() {
 //实例化一个命令行程序
 oApp := cli.NewApp()
 //程序名称
 oApp.Name = "GoTool"
 //程序的用途描述
 oApp.Usage = "To save the world"
 //程序的版本号
 oApp.Version = "1.0.0"
 //该程序执行的代码
 oApp.Action = func(c *cli.Context) error {
 fmt.Println("Test")
 return nil
 }
 //启动
 if err := oApp.Run(os.Args); err != nil {
 log.Fatal(err)
 }
 /*
 result:
 [root@localhost cli]# go run main.go help
  
 NAME:
 GoTool - To save the world
  
 USAGE:
 main [global options] command [command options] [arguments...]
  
 VERSION:
 1.0.0
  
 COMMANDS:
 help, h Shows a list of commands or help for one command
  
 GLOBAL OPTIONS:
 --help, -h  show help
 --version, -v print the version
  
 [root@localhost cli]# go run main.go 
 Test
 */ 
}

我们看到运行 go run main.go help 之后会输出一些帮助信息,说明你的程序已经成功成为一个命令行程序,接着使用命令 go run main.go 运行这个程序,结果是打印了Test信息,所以这个程序实际运行的函数由oApp.Action来控制,你后面的代码应该都在这个函数的内部去实现。

package main

import (
    "fmt"
    "log"
    "os"

    "github.com/urfave/cli"
)

func main() {
    //实例化一个命令行程序
    oApp := cli.NewApp()
    //程序名称
    oApp.Name = "GoTool"
    //程序的用途描述
    oApp.Usage = "To save the world"
    //程序的版本号
    oApp.Version = "1.0.0"

    //预置变量
    var host string
    var debug bool

    //设置启动参数
    oApp.Flags = []cli.Flag{
        //参数类型string,int,bool
        cli.StringFlag{
            Name:        "host",           //参数名字
            Value:       "127.0.0.1",      //参数默认值
            Usage:       "Server Address", //参数功能描述
            Destination: &host,            //接收值的变量
        },
        cli.IntFlag{
            Name:  "port,p",
            Value: 8888,
            Usage: "Server port",
        },
        cli.BoolFlag{
            Name:        "debug",
            Usage:       "debug mode",
            Destination: &debug,
        },
    }

    //该程序执行的代码
    oApp.Action = func(c *cli.Context) error {
        fmt.Printf("host=%v 
", host)
        fmt.Printf("port=%v 
", c.Int("port")) //不使用变量接收,直接解析
        fmt.Printf("debug=%v 
", debug)
        return nil
    }
    //启动
    if err := oApp.Run(os.Args); err != nil {
        log.Fatal(err)
    }
}

运行:

# go run cli.go --port 7777 
host=127.0.0.1 
port=7777 
debug=false  

执行 go run main.go --port 7777 之后,可以看到输出了设定的7777端口而非默认的8888端口,而服务器地址(host)和调试模式(debug)都输出了默认的数值。

如果第三方人员第一次使用你的程序也可以通过help命令看到可以设定的参数都有哪些,非常的人性化。