多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] 参考连接:[https://studygolang.com/articles/7588](https://studygolang.com/articles/7588) [github](https://github.com/spf13/cobra) ## Cobra提供的功能 * 简易的子命令行模式,如 app server, app fetch等等 * 完全兼容posix命令行模式 * 嵌套子命令subcommand * 支持全局,局部,串联flags * 使用Cobra很容易的生成应用程序和命令,使用cobra create appname和cobra add cmdname * 如果命令输入错误,将提供智能建议,如 app srver,将提示srver没有,是否是app server * 自动生成commands和flags的帮助信息 * 自动生成详细的help信息,如app help * 自动识别-h,--help帮助flag * 自动生成应用程序在bash下命令自动完成功能 * 自动生成应用程序的man手册 * 命令行别名 * 自定义help和usage信息 * 可选的紧密集成的[viper](http://github.com/spf13/viper)apps ## 示例 ``` package main import ( "fmt" "github.com/spf13/cobra" "github.com/spf13/viper" "os" ) //------自定义error------- type pubError struct { s string } func (pe *pubError) Error() string { return pe.s } //----------------------- var rootCmd = &cobra.Command{ Use: "demo", Short: "demo is a test cobra", 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`, RunE: func(cmd *cobra.Command, args []string) error { fmt.Println("demo Static Site Generator v0.9 -- HEAD") return &pubError{"123"} }, } func init() { rootCmd.PersistentFlags().StringP("config", "c", "config.json", "Configuration file to use.") rootCmd.PersistentFlags().Bool("platform", false, "This flag signifies that the user tried to start the command from the platform binary, so we can log a mssage") rootCmd.PersistentFlags().MarkHidden("platform") viper.SetEnvPrefix("demo") viper.BindEnv("config") viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config")) } func Execute() { if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } } func main() { Execute() } ```