4

I'm building a CLI tool to start learning some Go. I found this popular package that I wanted to use for some commands like this:

http://godoc.org/github.com/jessevdk/go-flags#Group
https://github.com/jessevdk/go-flags

ex list todos
ex list todos --completed
ex list events
ex list todos events
ex authenticate

The way I understand it is ex would be my main command.
list and authenticate are subcommands.

But what are todos and events in this scenario? And what would be --completed be. Is --completed called an Option? That's the verbage I see around, but not sure if I'm reading it correctly. I'm trying to find an example that has the different options for something like this scenario, but I could not find one.

I tried using urfave/cli which worked at well at first, until I found a requirement to be able to pass multiple entities to ex list like ex list todos events.

1 Answer 1

3

I have used jessevdk/go-flags on multiple projects and really like it. The documentation is sparse, but the code is clean so self-documenting in many ways.

I will try and address your questions as best I can:

ex would be your binary, and would usually be a 'master' struct of all the top level commands (eg https://github.com/concourse/concourse/blob/master/fly/commands/fly.go). This will get parsed in your main function (eg https://github.com/concourse/concourse/blob/master/fly/main.go).

todos and events would actually be the first level of subcommands. You would define those on the first level command (list) in the same way you define commands on the 'master' command struct.

--completed is indeed an option.

One example of an open source project that uses go-flags in the Concourse CI CLI https://github.com/concourse/concourse/tree/master/fly. Although it doesn't you nested commands like you want to do, it gives a pretty solid foundation for go-flags usage.

2
  • At the bottom of fly.go on line 50, there's var Fly FlyCommand. Why is this needed? Can you not reference the FlyCommand from another package without that declaration on line 50?
    – Crystal
    Aug 2, 2016 at 20:12
  • 2
    Yea, that's to create an actual 'instance' of the FlyCommand struct so that it can get populated with values. You'll see in the main() function that the address of that variable is passed in to the parser in NewParser(). Then when Parse() is called go-flags populates appropriate fields all the way through the command/options structure.
    – Corbin
    Aug 2, 2016 at 20:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.