从Codegansta CLI获取标志值

huangapple go评论84阅读模式
英文:

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)
    },
}

huangapple
  • 本文由 发表于 2015年10月31日 02:59:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/33443131.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定