An Interest In:
Web News this Week
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
How to add CLI subcommands in Go with Cobra
I made a small repo called good to regroup CLI commands and packages I like to use in Go:
Everything looks Good
Personal playground composed of CLI commands made in Go.
Disclaimer
Hacking cmd are provided for convenience and ethical hacking only. Don't use it to hack without explicit authorization (e.g., illegal activities).
Prerequisites
Add these lines to your .bashrc
or .zshrc
:
export GOPATH=$HOME/goexport PATH=$PATH:$GOROOT/bin:$GOPATH/bin
List of available commands
Fun commands
good fun catfact
: get absolutely essential facts about catsgood fun kanji
: get meanings and other info about a specific kanjigood fun spinthewheel
: Don't know what to decide? Maybe leave it to chance...good fun 1337
: Convert a string to leetspeak and shine on Internet
Checking tools
good check archi
: check your architecture with the Topology functiongood check bios
: check your BIOSgood check chassis
: check your chassis infogood check cpu
: check your CPUgood check gpu
: check your GPU
It's a mix of hacks and more "advanced" integrations to be used as CLI commands in the terminal.
I used Cobra, an incredible library to write CLI applications in Go.
Their documentation is pretty good and the package is quite easy to use. I had the need to "categorize" my commands, though. I don't pretend it's the best way to do it, but I like to use subcommands for that.
For example, in my repo, I use 3 categories:
- fun
- check
- hack
Cobra is very cool, as it automates lots of tasks in the terminal (usages, man documentation, suggestions, etc) and improves the user experience while abstracting the difficulty of developing CLI commands in Go. The following commands will display all CLI available for fun, checking hardware, and hacking:
good fungood checkgood hack
It's helpful even for me, as a maintainer.
To add subcommands, you can write the following in your package:
var rootCmd = &cobra.Command{ Use: "mycommand", Short: "short description",}var subCmd = &cobra.Command{ Use: "mysubcommand", Short: "short description",}
and then in the init
function:
func init() { rootCmd.AddCommand(subCmd)}
Users can type mycommand
and get mysubcommand
as a recommended usage.
Then, if I want to add a subcommand for mysubcommand
, I can register it like that:
subsubcommand = &cobra.Command{ Use: "subsubcommand", Short: "short description",}mysubcommand.AddCommand(subsubcommand)
Original Link: https://dev.to/jmau111/how-to-add-cli-subcommands-in-go-with-cobra-10ne
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To