简介

上一篇文章中,我们介绍了flag库。flag库是用于解析命令行选项的。但是flag有几个缺点:

  • 不显示支持短选项。当然上一篇文章中也提到过可以通过将两个选项共享同一个变量迂回实现,但写起来比较繁琐;
  • 选项变量的定义比较繁琐,每个选项都需要根据类型调用对应的TypeTypeVar函数;
  • 默认只支持有限的数据类型,当前只有基本类型bool/int/uint/stringtime.Duration

为了解决这些问题,出现了不少第三方解析命令行选项的库,今天的主角go-flags就是其中一个。第一次看到go-flags库是在阅读pgweb源码的时候。

go-flags提供了比标准库flag更多的选项。它利用结构标签(struct tag)和反射提供了一个方便、简洁的接口。它除了基本的功能,还提供了丰富的特性:

  • 支持短选项(-v)和长选项(—verbose);
  • 支持短选项合写,如-aux
  • 同一个选项可以设置多个值;
  • 支持所有的基础类型和 map 类型,甚至是函数;
  • 支持命名空间和选项组;
  • 等等。

上面只是粗略介绍了go-flags的特性,下面我们依次来介绍。

快速开始

学习从使用开始!我们先来看看go-flags的基本使用。

由于是第三方库,使用前需要安装,执行下面的命令安装:

  1. $ go get github.com/jessevdk/go-flags

代码中使用import导入该库:

  1. import "github.com/jessevdk/go-flags"

完整示例代码如下:

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/jessevdk/go-flags"
  5. )
  6. type Option struct {
  7. Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug message"`
  8. }
  9. func main() {
  10. var opt Option
  11. flags.Parse(&opt)
  12. fmt.Println(opt.Verbose)
  13. }

使用go-flags的一般步骤:

  • 定义选项结构,在结构标签中设置选项信息。通过shortlong设置短、长选项名字,description设置帮助信息。命令行传参时,短选项前加-,长选项前加--
  • 声明选项变量;
  • 调用go-flags的解析方法解析。

编译、运行代码(我的环境是 Win10 + Git Bash):

  1. $ go build -o main.exe main.go

短选项:

  1. $ ./main.exe -v
  2. [true]

长选项:

  1. $ ./main.exe --verbose
  2. [true]

由于Verbose字段是切片类型,每次遇到-v--verbose都会追加一个true到切片中。

多个短选项:

  1. $ ./main.exe -v -v
  2. [true true]

多个长选项:

  1. $ ./main.exe --verbose --verbose
  2. [true true]

短选项 + 长选项:

  1. $ ./main.exe -v --verbose -v
  2. [true true true]

短选项合写:

  1. $ ./main.exe -vvv
  2. [true true true]

基本特性

支持丰富的数据类型

go-flags相比标准库flag支持更丰富的数据类型:

  • 所有的基本类型(包括有符号整数int/int8/int16/int32/int64,无符号整数uint/uint8/uint16/uint32/uint64,浮点数float32/float64,布尔类型bool和字符串string)和它们的切片
  • map 类型。只支持键为string,值为基础类型的 map;
  • 函数类型。

如果字段是基本类型的切片,基本解析流程与对应的基本类型是一样的。切片类型选项的不同之处在于,遇到相同的选项时,值会被追加到切片中。而非切片类型的选项,后出现的值会覆盖先出现的值。

下面来看一个示例:

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/jessevdk/go-flags"
  5. )
  6. type Option struct {
  7. IntFlag int `short:"i" long:"int" description:"int flag value"`
  8. IntSlice []int `long:"intslice" description:"int slice flag value"`
  9. BoolFlag bool `long:"bool" description:"bool flag value"`
  10. BoolSlice []bool `long:"boolslice" description:"bool slice flag value"`
  11. FloatFlag float64 `long:"float", description:"float64 flag value"`
  12. FloatSlice []float64 `long:"floatslice" description:"float64 slice flag value"`
  13. StringFlag string `short:"s" long:"string" description:"string flag value"`
  14. StringSlice []string `long:"strslice" description:"string slice flag value"`
  15. PtrStringSlice []*string `long:"pstrslice" description:"slice of pointer of string flag value"`
  16. Call func(string) `long:"call" description:"callback"`
  17. IntMap map[string]int `long:"intmap" description:"A map from string to int"`
  18. }
  19. func main() {
  20. var opt Option
  21. opt.Call = func (value string) {
  22. fmt.Println("in callback: ", value)
  23. }
  24. _, err := flags.Parse(&opt)
  25. if err != nil {
  26. fmt.Println("Parse error:", err)
  27. return
  28. }
  29. fmt.Printf("int flag: %v\n", opt.IntFlag)
  30. fmt.Printf("int slice flag: %v\n", opt.IntSlice)
  31. fmt.Printf("bool flag: %v\n", opt.BoolFlag)
  32. fmt.Printf("bool slice flag: %v\n", opt.BoolSlice)
  33. fmt.Printf("float flag: %v\n", opt.FloatFlag)
  34. fmt.Printf("float slice flag: %v\n", opt.FloatSlice)
  35. fmt.Printf("string flag: %v\n", opt.StringFlag)
  36. fmt.Printf("string slice flag: %v\n", opt.StringSlice)
  37. fmt.Println("slice of pointer of string flag: ")
  38. for i := 0; i < len(opt.PtrStringSlice); i++ {
  39. fmt.Printf("\t%d: %v\n", i, *opt.PtrStringSlice[i])
  40. }
  41. fmt.Printf("int map: %v\n", opt.IntMap)
  42. }

基本类型和其切片比较简单,就不过多介绍了。值得留意的是基本类型指针的切片,即上面的PtrStringSlice字段,类型为[]*string
由于结构中存储的是字符串指针,go-flags在解析过程中遇到该选项会自动创建字符串,将指针追加到切片中。

运行程序,传入--pstrslice选项:

  1. $ ./main.exe --pstrslice test1 --pstrslice test2
  2. slice of pointer of string flag:
  3. 0: test1
  4. 1: test2

另外,我们可以在选项中定义函数类型。该函数的唯一要求是有一个字符串类型的参数。解析中每次遇到该选项就会以选项值为参数调用这个函数。
上面代码中,Call函数只是简单的打印传入的选项值。运行代码,传入--call选项:

  1. $ ./main.exe --call test1 --call test2
  2. in callback: test1
  3. in callback: test2

最后,go-flags还支持 map 类型。虽然限制键必须是string类型,值必须是基本类型,也能实现比较灵活的配置。
map类型的选项值中键-值通过:分隔,如key:value,可设置多个。运行代码,传入--intmap选项:

  1. $ ./main.exe --intmap key1:12 --intmap key2:58
  2. int map: map[key1:12 key2:58]

常用设置

go-flags提供了非常多的设置选项,具体可参见文档。这里重点介绍两个requireddefault

required非空时,表示对应的选项必须设置值,否则解析时返回ErrRequired错误。

default用于设置选项的默认值。如果已经设置了默认值,那么required是否设置并不影响,也就是说命令行参数中该选项可以没有。

看下面示例:

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "github.com/jessevdk/go-flags"
  6. )
  7. type Option struct {
  8. Required string `short:"r" long:"required" required:"true"`
  9. Default string `short:"d" long:"default" default:"default"`
  10. }
  11. func main() {
  12. var opt Option
  13. _, err := flags.Parse(&opt)
  14. if err != nil {
  15. log.Fatal("Parse error:", err)
  16. }
  17. fmt.Println("required: ", opt.Required)
  18. fmt.Println("default: ", opt.Default)
  19. }

运行程序,不传入default选项,Default字段取默认值,不传入required选项,执行报错:

  1. $ ./main.exe -r required-data
  2. required: required-data
  3. default: default
  4. $ ./main.exe -d default-data -r required-data
  5. required: required-data
  6. default: default-data
  7. $ ./main.exe
  8. the required flag `/r, /required' was not specified
  9. 2020/01/09 18:07:39 Parse error:the required flag `/r, /required' was not specified

高级特性

选项分组

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "os"
  6. "github.com/jessevdk/go-flags"
  7. )
  8. type Option struct {
  9. Basic GroupBasicOption `description:"basic type" group:"basic"`
  10. Slice GroupSliceOption `description:"slice of basic type" group:"slice"`
  11. }
  12. type GroupBasicOption struct {
  13. IntFlag int `short:"i" long:"intflag" description:"int flag"`
  14. BoolFlag bool `short:"b" long:"boolflag" description:"bool flag"`
  15. FloatFlag float64 `short:"f" long:"floatflag" description:"float flag"`
  16. StringFlag string `short:"s" long:"stringflag" description:"string flag"`
  17. }
  18. type GroupSliceOption struct {
  19. IntSlice int `long:"intslice" description:"int slice"`
  20. BoolSlice bool `long:"boolslice" description:"bool slice"`
  21. FloatSlice float64 `long:"floatslice" description:"float slice"`
  22. StringSlice string `long:"stringslice" description:"string slice"`
  23. }
  24. func main() {
  25. var opt Option
  26. p := flags.NewParser(&opt, flags.Default)
  27. _, err := p.ParseArgs(os.Args[1:])
  28. if err != nil {
  29. log.Fatal("Parse error:", err)
  30. }
  31. basicGroup := p.Command.Group.Find("basic")
  32. for _, option := range basicGroup.Options() {
  33. fmt.Printf("name:%s value:%v\n", option.LongNameWithNamespace(), option.Value())
  34. }
  35. sliceGroup := p.Command.Group.Find("slice")
  36. for _, option := range sliceGroup.Options() {
  37. fmt.Printf("name:%s value:%v\n", option.LongNameWithNamespace(), option.Value())
  38. }
  39. }

上面代码中我们将基本类型和它们的切片类型选项拆分到两个结构体中,这样可以使代码看起来更清晰自然,特别是在代码量很大的情况下。
这样做还有一个好处,我们试试用--help运行该程序:

  1. $ ./main.exe --help
  2. Usage:
  3. D:\code\golang\src\github.com\go-quiz\go-daily-lib\go-flags\group\main.exe [OPTIONS]
  4. basic:
  5. /i, /intflag: int flag
  6. /b, /boolflag bool flag
  7. /f, /floatflag: float flag
  8. /s, /stringflag: string flag
  9. slice:
  10. /intslice: int slice
  11. /boolslice bool slice
  12. /floatslice: float slice
  13. /stringslice: string slice
  14. Help Options:
  15. /? Show this help message
  16. /h, /help Show this help message

输出的帮助信息中,也是按照我们设定的分组显示了,便于查看。

子命令

go-flags支持子命令。我们经常使用的 Go 和 Git 命令行程序就有大量的子命令。例如go versiongo buildgo rungit statusgit commit这些命令中version/build/run/status/commit就是子命令。
使用go-flags定义子命令比较简单:

  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "log"
  6. "strconv"
  7. "strings"
  8. "github.com/jessevdk/go-flags"
  9. )
  10. type MathCommand struct {
  11. Op string `long:"op" description:"operation to execute"`
  12. Args []string
  13. Result int64
  14. }
  15. func (this *MathCommand) Execute(args []string) error {
  16. if this.Op != "+" && this.Op != "-" && this.Op != "x" && this.Op != "/" {
  17. return errors.New("invalid op")
  18. }
  19. for _, arg := range args {
  20. num, err := strconv.ParseInt(arg, 10, 64)
  21. if err != nil {
  22. return err
  23. }
  24. this.Result += num
  25. }
  26. this.Args = args
  27. return nil
  28. }
  29. type Option struct {
  30. Math MathCommand `command:"math"`
  31. }
  32. func main() {
  33. var opt Option
  34. _, err := flags.Parse(&opt)
  35. if err != nil {
  36. log.Fatal(err)
  37. }
  38. fmt.Printf("The result of %s is %d", strings.Join(opt.Math.Args, opt.Math.Op), opt.Math.Result)
  39. }

子命令必须实现go-flags定义的Commander接口:

  1. type Commander interface {
  2. Execute(args []string) error
  3. }

解析命令行时,如果遇到不是以---开头的参数,go-flags会尝试将其解释为子命令名。子命令的名字通过在结构标签中使用command指定。
子命令后面的参数都将作为子命令的参数,子命令也可以有选项。

上面代码中,我们实现了一个可以计算任意个整数的加、减、乘、除子命令math

接下来看看如何使用:

  1. $ ./main.exe math --op + 1 2 3 4 5
  2. The result of 1+2+3+4+5 is 15
  3. $ ./main.exe math --op - 1 2 3 4 5
  4. The result of 1-2-3-4-5 is -13
  5. $ ./main.exe math --op x 1 2 3 4 5
  6. The result of 1x2x3x4x5 is 120
  7. $ ./main.exe math --op ÷ 120 2 3 4 5
  8. The result of 120÷2÷3÷4÷5 is 1

注意,不能使用乘法符号*和除法符号/,它们都不可识别。

其他

go-flags库还有很多有意思的特性,例如支持 Windows 选项格式(/v/verbose)、从环境变量中读取默认值、从 ini 文件中读取默认设置等等。大家有兴趣可以自行去研究~

参考

  1. go-flagsGithub 仓库
  2. go-flagsGoDoc 文档