Cobra-CLI将所有参数和标志传递给可执行文件
我为自己的东西有一个眼镜蛇CLI。现在,我想添加常用的可执行文件 eg kubectl
, calicoctl
作为子命令,将消耗所有参数和标志,例如
mywrapper kubectl get all --all-namespaces
mywrapper kubectl create deployment nginx --image=nginx --port=80
复制COBRA Project
mkdir mywrapper; cd mywrapper; go mod init mywrapper; cobra-cli init .
并添加一个subcommand eg kubectl
cobra-cli add kubectl
然后填充 ./ cmd/kubectl.go
,
package cmd
import (
"fmt"
"os/exec"
"strings"
"github.com/spf13/cobra"
)
var kubectlCmd = &cobra.Command{
Use: "kubectl",
Short: "run kubectl",
Run: func(cmd *cobra.Command, args []string) {
out, err := exec.Command("/bin/bash", "-c", fmt.Sprintf("kubectl %v", strings.Join(args, " "))).Output()
if err != nil {
fmt.Println(err)
}
fmt.Println(string(out))
},
}
func init() {
rootCmd.AddCommand(kubectlCmd)
}
我现在可以运行 kubectl
命令 eg 进行运行。 kubectl获取豆荚
。但是,当添加标志 eg 时,它会失败。 kubectl获取豆荚-Selector App = nginx
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在
之后传递标志 -
。双仪表( - )用于表示命令选项的结尾。在我们的情况下,需要区分传递给go
的标志和那些没有的标志。双重破折号之后的所有内容都不会被视为go
的标志。我尝试使用GCLOUD:
然后尝试:
添加更多标志:
Pass your flags after the
--
. A double dash (--) is used to signify the end of command options. In our case it is required to distinguish between the flags passed togo
and those that aren't. Everything after the double dash wont be considered to bego
's flags.I tried with gcloud:
Then tried:
Adding more flags: