In this post, I will provide information about building a go program with arguments and options.
Typically, an executable can contain
- Arguments: Go expects these to be provided after all the options.
- options (specified with - & provided with an option value). Example: "-srcDir /tmp". Go calls these as "flags".
- flags: True if specified, else false. Example: "-e" to enable/disable. Go doesn't support this type of flags !!!
Here is a sample binary I built to test go flags. Sample outputs running the above binary:
- How to get help text?
So, we get help text free if we use flags package !!
- Run the program without any inputs:
- Run the program without any additional arguments
- Run the program with an additional argument
Some drawbacks I see with go flags package:
- As we saw earlier, go flags package doesn't provide a way for us to specify mandatory options. We need to either write additional code (like I provided above) or use custom packages such as go-flags
- go doesn't support true/false kind of flags
TBD:
- flagSet (building subcommands)
References:
https://blog.rapid7.com/2016/08/04/build-a-simple-cli-tool-with-golang/
https://gobyexample.com/command-line-flags
https://stackoverflow.com/questions/31786215/can-command-line-flags-in-go-be-set-to-mandatory/31786480#:~:text=The%20flag%20package%20does%20not,halt%20with%20an%20error%20message