最开始的解析命令行参数是使用的标准库里面的flag包,后来想增长新的参数的时候比较复杂和困难,所以使用cobra更加简单一些html
好比执行go-fly server port 8081是运行项目git
执行go-fly install是导入数据库github
目录结构:数据库
增长cmd目录,做为cmd包,代码中直接定义全局变量和可导出的函数 , root.go里面是这样的ide
package cmd import ( "errors" "fmt" "github.com/spf13/cobra" "os" ) var rootCmd = &cobra.Command{ Use: "go-fly", Short: "go-fly", Long: `简洁快速的GO语言WEB在线客服 https://gofly.sopans.com`, Args:args, Run: func(cmd *cobra.Command, args []string) { }, } func args(cmd *cobra.Command, args []string) error{ if len(args)<1{ return errors.New("至少须要一个参数!") } return nil } func Execute() { if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } } func init() { rootCmd.AddCommand(versionCmd) rootCmd.AddCommand(serverCmd) rootCmd.AddCommand(installCmd) }
在入口文件中直接调用Excute方法进行使用函数
package main import ( "github.com/taoshihan1991/imaptool/cmd" ) func main() { cmd.Execute() }
AddCommand就是在增长参数,好比versionCmd这个实例,定义在了version.go里面 ,执行go-fly version的时候打印版本号post
package cmd import ( "fmt" "github.com/spf13/cobra" "github.com/taoshihan1991/imaptool/config" ) var versionCmd = &cobra.Command{ Use: "version", Short: "example:go-fly version", Run: func(cmd *cobra.Command, args []string) { fmt.Println("go-fly "+config.Version) }, }
直接访问效果:spa
加上参数效果:命令行