Cookiecutter Template for Writing Go Command Line Interface
I have been developing a lot of Go language based CLIs and most of them have similar structure. And every time I start a new project I tend to rewrite the same structure. So, instead of doing that I copied the required code and turned in into a cookiecutter template 😎.
The repository is available at - github.com/akshaybabloo/go-cli-template.
<p>This template is highly inspired by <a href="https://github.com/cli/cli">GitHub’s CLI</a>.</p>
Requirements
- Python 3.6+
- Install cookiecutter
- Go 1.16+
Usage
In your terminal type in
> cookiecutter https://github.com/akshaybabloo/go-cli-template
Then, follow the options on the terminal.
Once done, you will have to refactor the module path in go.mod
to suit your project name, I usually have it as github.com/akshaybabloo/<project-name>
.
Features
- Checks for updates once every 24 hours via GitHub API
- Uses Cobra package for CLI
- Factory based approach, functions are available on every command if needed
- Global debug flag - uses logrus
- Custom help output that also displays aliases
- Uses custom color that’s available via factory - uses color
- Default global configuration location -
<user folder>/<project name>/config.yaml
- Disable colour usage globally
Packages Used
Built using great open-source packages:
- heredoc - Package heredoc provides the here-document with keeping indent
- GitHub CLI - GitHub command line tool package
- color - Colour package
- uuid - UUID generator
- go-version - A library for parsing and verifying versions and version constraints
- logrus - Structured, pluggable logging for Go.
- afero - Afero is a filesystem framework providing a simple, uniform and universal API interacting with any filesystem
- Cobra - Cobra is both a library for creating powerful modern CLI applications
- pflags - pflag is a drop-in replacement for Go’s flag package, implementing POSIX/GNU-style –flags
- testify - A toolkit with common assertions and mocks that plays nicely with the standard library
- YAML v3 - YAML support for the Go language
Conclusion
I hope this template is able to help you with your next project. Happy coding 😄.