githubcomspf13cobra 软件的使用实例举5个代码实例。
- 创建一个简单的命令:
var rootCmd = &cobra.Command{
Use: "myapp",
Short: "A brief description of your application",
Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your application.`,
Run: func(cmd *cobra.Command, args []string) {
// Do Stuff Here
},
}
func main() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
- 添加一个子命令:
var rootCmd = &cobra.Command{
Use: "myapp",
Short: "A brief description of your application",
Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your application.`,
Run: func(cmd *cobra.Command, args []string) {
// Do Stuff Here
},
}
var subCmd = &cobra.Command{
Use: "sub",
Short: "A brief description of your subcommand",
Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your subcommand.`,
Run: func(cmd *cobra.Command, args []string) {
// Do Subcommand Stuff Here
},
}
func init() {
rootCmd.AddCommand(subCmd)
}
func main() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
- 添加一个标志:
var rootCmd = &cobra.Command{
Use: "myapp",
Short: "A brief description of your application",
Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your application.`,
Run: func(cmd *cobra.Command, args []string) {
// Do Stuff Here
},
}
var myFlag string
func init() {
rootCmd.Flags().StringVar(&myFlag, "myflag", "default", "A brief description of my flag")
}
func main() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
- 添加一个参数:
var rootCmd = &cobra.Command{
Use: "myapp",
Short: "A brief description of your application",
Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your application.`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
// Do Stuff Here
},
}
func main() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
- 添加一个可选参数:
var rootCmd = &cobra.Command{
Use: "myapp",
Short: "A brief description of your application",
Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your application.`,
Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
// Do Stuff Here
},
}
func main() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
``
原文地址: https://www.cveoy.top/t/topic/chwS 著作权归作者所有。请勿转载和采集!