从Codegansta CLI获取标志值

时间:2015-10-30 18:59:16

标签: go command-line-interface

我在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

我做错了什么?

1 个答案:

答案 0 :(得分:3)

使用app.Flags方法访问Context.Global*中定义的标志。

你想要

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