命令行解析cobra使用 发表于 2017-11-07 | 分类于 go | 示例代码 cobra是go的命令解析工具库,解析命令行参数。 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253package mainimport ( "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 love by spf13 and friends in Go. Complete documentation is available at http://hugo.spf13.com`, Run: func(cmd *cobra.Command, args []string) { // Do Stuff Here },}var param stringfunc init() { RootCmd.AddCommand(startCmd) f := startCmd.Flags() f.StringVarP(¶m, "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) }} 相关链接 cobra cobra example 本文标题:命令行解析cobra使用 文章作者:Louis 发布时间:2017年11月07日 - 20:11 最后更新:2017年11月07日 - 20:11 原始链接:/2017/11/07/go-cobra/ 许可协议: Louis-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。