命令行解析cobra使用

示例代码

cobra是go的命令解析工具库,解析命令行参数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package main
import (
"fmt"
"os"
"github.com/spf13/cobra"
)
var RootCmd = &cobra.Command{
Use: "hugo",
Short: "Hugo is a very fast static site generator",
Long: A Fast and Flexible Static Site Generator built with</span></div><div class="line"><span class="string"> love by spf13 and friends in Go.</span></div><div class="line"><span class="string"> Complete documentation is available at http://hugo.spf13.com,
Run: func(cmd *cobra.Command, args []string) {
},
}
var param string
func () {
RootCmd.AddCommand(startCmd)
f := startCmd.Flags()
f.StringVarP(&param, "param", "p", "", "Source directory to read from")
RootCmd.AddCommand(versionCmd)
}
var versionCmd = &cobra.Command{
Use: "version",
Short: "Print the version number of Hugo",
Long: All software has versions. This is Hugo's,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")
},
}
var startCmd = &cobra.Command{
Use: "start",
Short: "run Hugo",
Long: run,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("param is ", param)
},
}
func main() {
if err := RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}

相关链接

  1. cobra
  2. cobra example