英文:
Get flag value from Codegansta CLI
问题
我正在使用Go编写一个命令行应用程序,并希望将Redis端点指定为标志。我已经添加了以下内容:
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "redis, r",
Value: "127.0.0.1",
Usage: "redis host to listen to",
EnvVar: "REDIS_URL",
},
}
然而,在我的命令中,该标志始终为空:
return cli.Command{
Name: "listen",
Usage: "Listen to a stream",
Action: func(c *cli.Context) {
redisUrl := c.String("redis")
log.Printf("Connecting to redis: %s\n", redisUrl)
},
}
使用以下命令调用:
./mantle-monitor --redis 127.0.0.1 listen
我做错了什么?
英文:
I'm writing a command line app in Go and want to specify a redis endpoint as a flag. I've added the following:
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "redis, r",
Value: "127.0.0.1",
Usage: "redis host to listen to",
EnvVar: "REDIS_URL",
},
}
However, in my command, the flag is always blank:
return cli.Command{
Name: "listen",
Usage: "Listen to a stream",
Action: func(c *cli.Context) {
redisUrl := c.String("redis")
log.Printf("Connecting to redis: %s\n", redisUrl)
},
}
Invoked with:
./mantle-monitor --redis 127.0.0.1 listen
What am I doing wrong?
答案1
得分: 3
在app.Flags
中定义的标志可以通过Context.Global*
方法访问。
你想要的代码如下:
return cli.Command{
Name: "listen",
Usage: "监听流",
Action: func(c *cli.Context) {
redisUrl := c.GlobalString("redis")
log.Printf("连接到redis:%s\n", redisUrl)
},
}
英文:
Flags defined in app.Flags
are accessed with the Context.Global*
methods.
You want
return cli.Command{
Name: "listen",
Usage: "Listen to a stream",
Action: func(c *cli.Context) {
redisUrl := c.GlobalString("redis")
log.Printf("Connecting to redis: %s\n", redisUrl)
},
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论