flag包
原则
- 标志前使用 - 和 – 都可以; 标志后带不带=都可以(bool除外)
- bool flag可选值: 1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False
- 必须使用 -flag=false 的形式. (规避 cmd -x * 对文件列表使用命令时,有文件名是0,false等)
简单指针
var strIpt = flag.String("string", "John", "字符串输入")
var intIpt = flag.Int("int", 1, "int输入")
var int64Ipt = flag.Int64("int64", 1, "int64输入")
var float64Ipt = flag.Float64("float64", 1, "float64输入")
var boolIpt = flag.Bool("bool", false, "bool输入")
var durationIpt = flag.Duration("duration", time.Second, "duration输入")
// test with: go run main.go --string "i'm liming" --int 50 --bool=false -duration 1h30m
func ShowSimplePtr() {
flag.Parse()
inputArr := [...]interface{}{strIpt, intIpt, int64Ipt, float64Ipt, boolIpt, durationIpt}
for _, item := range inputArr {
val := reflect.ValueOf(item)
fmt.Printf("input flag type: %T ; input value: %v. \n", item, val.Elem())
}
}运行时变量
// go run main.go --strval liming -s danny
// go run main.go --s liming -strval danny
// 变量赋值方法:StringVal, BoolVar, DurationVal, Float64Val, Int64Val, IntVal, Uint64Val, UintVal
func ShowCustomVar() {
var strValIpt string
const (
defaultValue = "slay"
usage = "这是一段使用说明"
)
flag.StringVar(&strValIpt, "strval", defaultValue, usage)
flag.StringVar(&strValIpt, "s", defaultValue, usage+" (shorthand)")
flag.Parse()
fmt.Printf("input flag type: %T ; input value: %v. \n", strValIpt, strValIpt)
}简单钩子函数
// go run main.go --ip=127.0.0.1
func ShowHookFunc() {
var ip net.IP
flag.Func("ip", "IP address to parse", func(s string) error {
ip = net.ParseIP(s)
if ip == nil {
return errors.New("parse IP failed")
}
return nil
})
flag.Parse()
fmt.Printf("input flag type: %T ; input value: %v. \n", ip, ip)
}复杂钩子函数
// go run main.go --string liming --bool --int 20
// type Flag struct {
// Name string // name as it appears on command line
// Usage string // help message
// Value Value // value as set
// DefValue string // default value (as text); for usage message
// }
func ShowComplexHook() {
flag.Parse()
flag.Visit(func(f *flag.Flag) {
fmt.Printf("flag name: %v, value: %v \n", f.Name, f.Value)
switch f.Name {
case "string":
f.Value.Set("xiaohong")
case "int":
intIpt := f.Value.String()
strictInt, _ := strconv.Atoi(intIpt)
strictInt *= 10
f.Value.Set(strconv.Itoa(strictInt))
}
})
// flag.VisitAll(fn func(*Flag)) 可以遍历所有的标志参数(包括未被设置的)
strFlagPtr := flag.Lookup("string")
fmt.Printf("flagPtr : %#v \n", strFlagPtr)
intFlagPtr := flag.Lookup("int")
fmt.Printf("flagPtr : %v \n", intFlagPtr)
}参数列表
// go run main.go --string liming today --int 50 --bool=false -duration 1h30m hel
func ShowArgs() {
flag.Parse()
// 返回非标志命令行参数(返回格式:字符串数组)
nonFlag := flag.Args()
fmt.Println(nonFlag)
secParam := flag.Arg(1)
fmt.Println(secParam)
notFlagNum := flag.NArg()
fmt.Println(notFlagNum)
// go run main.go --string liming --int 50 --bool=false -duration 1h30m hel
flagNum := flag.NFlag()
fmt.Println(flagNum)
}独立标志
// FlagSet 提供了定义独立标志集的功能
// const (
// ContinueOnError ErrorHandling = iota // Return a descriptive error.
// ExitOnError // Call os.Exit(2) or for -h/-help Exit(0).
// PanicOnError // Call panic with a descriptive error.
// )
// go run main.go foo --name=kity --enable x y z
// go run main.go bar --level 9 10 11
func ShowFlagSet() {
fooCmd := flag.NewFlagSet("foo", flag.ExitOnError)
fooEnable := fooCmd.Bool("enable", false, "enable")
fooName := fooCmd.String("name", "", "name")
// fooCmd.PrintDefaults()
barCmd := flag.NewFlagSet("bar", flag.ContinueOnError)
barLevel := barCmd.Int("level", 0, "level")
if len(os.Args) < 2 {
fmt.Println("expected 'foo' or 'bar' subcommands")
os.Exit(1)
}
switch os.Args[1] {
case "foo":
fooCmd.Parse(os.Args[2:])
fmt.Println("subcommand 'foo'")
fmt.Println(" enable:", *fooEnable)
fmt.Println(" name:", *fooName)
fmt.Println(" tail:", fooCmd.Args())
case "bar":
barCmd.Parse(os.Args[2:])
fmt.Println("subcommand 'bar'")
fmt.Println(" level:", *barLevel)
fmt.Println(" tail:", barCmd.Args())
default:
fmt.Println("expected 'foo' or 'bar' subcommands")
os.Exit(1)
}
}第三方库
猛如虎
- argparse - Command line argument parser inspired by Python’s argparse module.
- argv - Go library to split command line string as arguments array using the bash syntax.
- cli - Feature-rich and easy to use command-line package based on golang struct tags.
- cli - Simple and complete API for building command line interfaces in Go.
- climax - Alternative CLI with “human face”, in spirit of Go command.
- clîr - A Simple and Clear CLI library. Dependency free.
- cmd - Extends the standard
flagpackage to support sub commands and more in idomatic way. - cmdr - A POSIX/GNU style, getopt-like command-line UI Go library.
- cobra - Commander for modern Go CLI interactions.
- command-chain - A go library for configure and run command chains - such like pipelining in unix shells.
- commandeer - Dev-friendly CLI apps: sets up flags, defaults, and usage based on struct fields and tags.
- complete - Write bash completions in Go + Go command bash completion.
- Dnote - A simple command line notebook with multi-device sync.
- env - Tag-based environment configuration for structs.
- flag - Simple but powerful command line option parsing library for Go supporting subcommand.
- flaggy - A robust and idiomatic flags package with excellent subcommand support.
- flagvar - A collection of flag argument types for Go’s standard
flagpackage. - go-andotp - A CLI program to encrypt/decrypt andOTP files. Can be used as library as well.
- go-arg - Struct-based argument parsing in Go.
- go-commander - Go library to simplify CLI workflow.
- go-flags - go command line option parser.
- go-getoptions - Go option parser inspired on the flexibility of Perl’s GetOpt::Long.
- gocmd - Go library for building command line applications.
- hiboot cli - cli application framework with auto configuration and dependency injection.
- job - JOB, make your short-term command as a long-term job.
- kingpin - Command line and flag parser supporting sub commands.
- liner - Go readline-like library for command-line interfaces.
- mitchellh/cli - Go library for implementing command-line interfaces.
- mow.cli - Go library for building CLI applications with sophisticated flag and argument parsing and validation.
- ops - Unikernel Builder/Orchestrator.
- pflag - Drop-in replacement for Go’s flag package, implementing POSIX/GNU-style –flags.
- sand - Simple API for creating interpreters and so much more.
- sflags - Struct based flags generator for flag, urfave/cli, pflag, cobra, kingpin and other libraries.
- strumt - Library to create prompt chain.
- ts - Timestamp convert & compare tool.
- ukautz/clif - Small command line interface framework.
- urfave/cli - Simple, fast, and fun package for building command line apps in Go (formerly codegangsta/cli).
- wlog - Simple logging interface that supports cross-platform color and concurrency.
- wmenu - Easy to use menu structure for cli applications that prompts users to make choices.
使用urfave/cli
功能特点: * 子命令 * flag和command区分 * 简写合并 * 自动补全(不同bash还有不同配置) * 随机值 * 从文件读取命令配置 * version-flag * 时间戳控件
func Command() {
app := &cli.App{
Commands: []*cli.Command{
{
Name: "add",
Aliases: []string{"a"},
Usage: "add a task to the list",
Action: func(c *cli.Context) error {
fmt.Println("added task: ", c.Args().First())
return nil
},
},
{
Name: "complete",
Aliases: []string{"c"},
Usage: "complete a task on the list",
Action: func(c *cli.Context) error {
fmt.Println("completed task: ", c.Args().First())
return nil
},
},
{
Name: "template",
Aliases: []string{"t"},
Usage: "options for task templates",
Subcommands: []*cli.Command{
{
Name: "add",
Usage: "add a new template",
Action: func(c *cli.Context) error {
fmt.Println("new task template: ", c.Args().First())
return nil
},
},
{
Name: "remove",
Usage: "remove an existing template",
Action: func(c *cli.Context) error {
fmt.Println("removed task template: ", c.Args().First())
return nil
},
},
},
},
},
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}