官方文档 : https://godoc.org/github.com/urfave/cli
提供了一个命令行框架。
go get github.com/urfave/cli
import “github.com/urfave/cli”
导入包
cli.NewApp()创建一个实例
调用Run()方法就实现了一个最基本的命令行程序了
app.Action 指定入口函数
package main
import (
"os"
"github.com/urfave/cli"
)
func main() {
app := cli.NewApp()
app.Name = "greet"
app.Usage = "say a greeting"
app.Action = func(c *cli.Context) error {
println("Greetings")
return nil
}
app.Run(os.Args)
}
运行1:
go run main.go --help
NAME:
greet - say a greeting
USAGE:
main.exe [global options] command [command options] [arguments…]
VERSION:
0.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
运行2:
go run main.go
Greetings
Flag 使用
package main
import (
"fmt"
"os"
"github.com/urfave/cli"
)
func main() {
var m_port int
app := cli.NewApp()
app.Name = "greet" // 指定程序名称
app.Usage = "say a greeting" // 程序功能描述
app.Flags = []cli.Flag{
cli.IntFlag{
Name: "port, p", // 配置名称
Value: 8000, // 缺省配置值
Usage: "listening port", // 配置描述
Destination: &m_port, // 保存配置值
},
}
app.Action = func(c *cli.Context) error {
println("Greetings")
fmt.Println(c.Int("port"))
fmt.Println(m_port)
return nil
}
app.Run(os.Args)
}
运行1:
go run main.go --help
NAME:
greet - say a greeting
USAGE:
main.exe [global options] command [command options] [arguments…]
VERSION:
0.0.0
COMMANDS:
help, h Shows a list of commands or help for one command
GLOBAL OPTIONS:
–port value, -p value listening port (default: 8000)
–help, -h show help
–version, -v print the version
运行2:
go run main.go
Greetings
8000
8000
运行3:
go run main.go --port=8080
Greetings
8080
8080
Command 使用
package main
import (
"fmt"
"os"
"github.com/urfave/cli"
)
func main() {
var m_port int
app := cli.NewApp()
app.Name