gpt4 book ai didi

没有参数匹配的 golang cobra 子命令

转载 作者:IT王子 更新时间:2023-10-29 01:26:21 25 4
gpt4 key购买 nike

我想用 cobra 创建 golang CLI .目前,它运行良好。我创建了类似 foobar create --username johndoe 的东西。但我需要像 foobar create user --username johndoe 这样的子命令。有 user 子命令。

我创建了参数匹配,

var applicationCmd = &cobra.Command{
Use: "application",
Short: "Create/Read/Update application",
Long: `You can create any user or partner.`,
Run: (cmd *cobra.Command, args []string) {
if len(args) < 1 {
fmt.Printf("%sPlease choose any object that you want to change e.g (user, partner)%s\n", chalk.Red, chalk.Reset)
}
if stringUtil.Contains(args, "user") {
createUser()
}
if stringUtil.Contains(args, "partner") {
createPartner()
}
},
}

但我认为使用 cobra 比使用像这样匹配的参数有更好的方法。有什么建议吗?

最佳答案

我有点过火了;但是,是的,appCmd.Addcommand(newCmd) 就是您要找的。

(在您发布答案之前我已经开始研究这个,但我不想废弃代码)

package main

import (
"github.com/spf13/cobra"
"fmt"
)

var rootCmd = &cobra.Command{
Use: "app",
Run: func (cmd *cobra.Command, args []string) {
},
}

var makeU = &cobra.Command{
Use: "makeU",
Short: "makes a user",
Long: "Prints stuff about the user. You could also use the flags in your addPartner() function",
Run: func (cmd *cobra.Command, args []string) {
fmt.Println("User's name: " + uName)
fmt.Println("User's number: " + uNumber)
fmt.Println("User's other stuff: " + uOtherStuff)
},
}

var makeP = &cobra.Command{
Use: "makeP",
Short: "makes a partner",
Long: "Prints stuff about the partner. You could also use the flags in your addPartner() function",
Run: func (cmd *cobra.Command, args []string) {
fmt.Println("Partner's name: " + uName)
fmt.Println("Partner's number: " + uNumber)
fmt.Println("Partner's other stuff: " + uOtherStuff)
},
}

// adds commands
func addCommands() {
rootCmd.AddCommand(makeU)
rootCmd.AddCommand(makeP)
}

// adds flags
var pName, pNumber, pOtherStuff string
var uName, uNumber, uOtherStuff string
func init() {
makeU.Flags().StringVar(&uName, "username", "default", "--username=<user's name>")
makeU.Flags().StringVar(&uNumber, "usernumber", "default", "--usernumber=<user's number>")
makeU.Flags().StringVar(&uOtherStuff, "userother", "default", "--userother=<user's other stuff>")
makeP.Flags().StringVar(&pName, "partnername", "default", "--partnername=<partner's name>")
makeP.Flags().StringVar(&pNumber, "partnernumber", "default", "--partnernumber=<partner's number>")
makeP.Flags().StringVar(&pOtherStuff, "partnerother", "default", "--partnerother=<partner's other stuff>")
}


func main() {
addCommands()
rootCmd.Execute()
}

关于没有参数匹配的 golang cobra 子命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47130308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com