package cmd import ( "log" "github.com/spf13/cobra" flag "github.com/spf13/pflag" ) var Source string // 这里初始化了flag 环境 var cliName = flag.StringP("name", "n", "Nick", "Input Your Name") var cliAuthor = flag.StringP("author", "a", "nameOfAuthor", "Input Author Name") var Verbose bool var versionCmd = &cobra.Command{ Use: "version", Short: "A brief description of your command", Long: `A longer description that spans multiple lines and likely contains examples and usage of using your command. For example: Cobra is a CLI library for Go that empowers applications. This application is a tool to generate the needed files to quickly create a Cobra application.`, Run: func(cmd *cobra.Command, args []string) { log.Println("version 1.0") log.Println("Source===>", Source) // 这里需要提前准备上面的这两行代码 // cmd.Flag("author") 这里有Lookup // var cliName = flag.StringP("name", "n", "Nick", "Input Your Name") // var cliAuthor = flag.StringP("author", "a", "nameOfAuthor", "Input Author Name") log.Println("cobra.command get cliName===>", cmd.Flag("author").Value) log.Println("cobra.command get cliAuthor===>", cmd.Flag("name").Value) log.Println("cliName===>", *cliName) log.Println("cliAuthor===>", *cliAuthor) log.Println(args) }, } func init() { rootCmd.AddCommand(versionCmd) rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "全局版本") versionCmd.Flags().StringVarP(&Source, "source", "s", "", "读取文件路径") }
输出...,命令行参数[ag1 ag2 xx]和选项参数-s /tmp都能传进来用
... 找个能入门的...
了解cobra 先看看 pflag
main.go
package main import ( "cobhu/cmd" ) func main() { cmd.Execute() }
version.go