简体   繁体   中英

Get flag value from Codegansta CLI

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM