Golang has built in support for creating CLI applications that accept command line flags and arguments. The “flag” package has convenient methods for reading in options as typed variables, it also supports creating default help text. CLI applications are useful for creating developer tooling, especially when you can import critical parts of the codebase into a simple cli.
Playground: https://go.dev/play/p/UHuXCNgQB8j
package main
import "flag"
var (
// define the command line arguments
customerID *int = flag.Int("customer-id", 0, "Customer ID")
customerName *string = flag.String("customer-name", "", "Customer Name")
cutsomerEmail *string = flag.String("customer-email", "", "Customer Email")
)
// build the binary
// go build -o customer-cli cli/flags/flags.go
// add a customer: ./customer-cli -customer-name=kyle -customer-email=contact@kfelter.com add
// update a customer: ./customer-cli -customer-id=3 -customer-name=kyle -customer-email=contact@kfelter.com update
// delete a customer: ./customer-cli -customer-id=3 delete
// print the usage: ./customer-cli
func main() {
// parse the command line arguments
flag.Parse()
// check the command
switch flag.Arg(0) {
case "add":
// add a customer
println("Add customer", *customerName, *cutsomerEmail)
case "update":
// update a customer
println("Update customer", *customerID, *customerName, *cutsomerEmail)
case "delete":
// delete a customer
println("Delete customer", *customerID)
default:
// invalid command, print the usage
println("Usage: [options] customer add|update|delete")
flag.PrintDefaults()
}
}