我使用https://github.com/spf13/cobra库创建了一个小型 Go 应用程序。我创建了一个新标志-tor --token,当我传递这个参数时,我希望应用程序打印它。这就是我所做的:func init() {
fmt.Println("[*] Inside init()")
var token string
rootCmd.PersistentFlags().StringVarP(&token, "token", "t", "", "Service account Token (JWT) to insert")
fmt.Println(token)
}但当我像这样运行应用程序时它不会打印它:.\consoleplay.exe --token "hello.token"如何打印标志的值。
1 回答

守候你守候我
TA贡献1802条经验 获得超10个赞
您无法在init()函数中打印令牌的值,因为该init()函数在第一次调用包时在运行时执行。该值尚未分配。
因此,您必须全局声明该变量并在命令Run的方法中使用它rootCmd。
var token string
var rootCmd = &cobra.Command{
Use: "consoleplay",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println(token)
},
}
func init() {
rootCmd.Flags().StringVarP(&token, "token", "t", "", "usage")
}
- 1 回答
- 0 关注
- 118 浏览
添加回答
举报
0/150
提交
取消