SoFunction
Updated on 2025-03-03

Usage instructions for basic command line module urfave/cli in Golang

Preface

I believe that as long as you have deployed online services, you know that startup parameters are essential. When you start a service in different network, hardware, and software environments, there will always be some startup parameters that are uncertain. At this time, you need to parse these parameters through the command line module. urfave/cli is a simple and practical command line tool in Golang.

Install

The installation can be completed through the go get /urfave/cli command.

text

After using urfave/cli, your program will become a command line program. The following is the simplest command line program created through urfave/cli. It sets some basic information, and the program ends up simply printing the Test information.

package main 
import (
 "/urfave/cli"
 "os"
 "log"
 "fmt"
)
 
func main() {
 //Instantiate a command line program oApp := ()
 //Program name  = "GoTool"
 //Description of the application of the program  = "To save the world"
 //Program version number  = "1.0.0"
 //The code executed by the program  = func(c *) error {
 ("Test")
 return nil
 }
 //start up if err := (); err != nil {
 (err)
 }
 /*
 result:
 [root@localhost cli]# go run  help
 
 NAME:
 GoTool - To save the world
 
 USAGE:
 main [global options] command [command options] [arguments...]
 
 VERSION:
 1.0.0
 
 COMMANDS:
 help, h Shows a list of commands or help for one command
 
 GLOBAL OPTIONS:
 --help, -h  show help
 --version, -v print the version
 
 [root@localhost cli]# go run  
 Test
 */ 
}

We see that after running go run help, some help information will be output, indicating that your program has successfully become a command line program. Then use the command go run to run the program, and the test information is printed, so the functions that the program actually runs are controlled, and the code you subsequently should be implemented inside this function.

Next, we set some common startup parameters, which are very simple, the code is as follows

package main 
import (
 "/urfave/cli"
 "os"
 "log"
 "fmt"
)
 
func main() {
 //Instantiate a command line program oApp := ()
 //Program name  = "GoTool"
 //Description of the application of the program  = "To save the world"
 //Program version number  = "1.0.0"
 
 //Preset variable var host string
 var debug bool
 
 //Set startup parameters  = []{
 // Parameter type string, int, bool {
 Name:  "host",   // Parameter name Value:  "127.0.0.1",  //Default value of parameters Usage:  "Server Address", //Parameter function description Destination: &host,   //Variable of received value },
 {
 Name:  "port,p",
 Value:  8888,
 Usage:  "Server port",
 },
 {
 Name:  "debug",
 Usage:  "debug mode",
 Destination: &debug,
 },
 }
 
 //The code executed by the program  = func(c *) error {
 ("host=%v \n",host)
 ("host=%v \n",("port")) //Do not use variable reception, directly parse ("host=%v \n",debug)
 /*
 result:
 [root@localhost cli]# go run  --port 7777
 host=127.0.0.1 
 host=7777 
 host=false 
 
 [root@localhost cli]# go run  help
 NAME:
  GoTool - To save the world
 
 USAGE:
  main [global options] command [command options] [arguments...]
 
 VERSION:
  1.0.0
 
 COMMANDS:
 help, h Shows a list of commands or help for one command
 
 GLOBAL OPTIONS:
  --host value   Server Address (default: "127.0.0.1")
  --port value, -p value Server port (default: 8888)
  --debug     debug mode
  --help, -h    show help
  --version, -v   print the version
 */
 return nil
 }
 //start up if err := (); err != nil {
 (err)
 } 
}

After executing go run --port 7777, you can see that the set 7777 port is output instead of the default 8888 port, while the server address (host) and debug mode (debug) both output the default values.

If a third-party person uses your program for the first time, you can also see what parameters you can set through the help command, which is very user-friendly.

Of course, urfave/cli also allows us to set multiple commands, and different commands perform different operations, as follows

package main 
import (
 "/urfave/cli"
 "os"
 "log"
 "fmt"
)
 
func main() {
 //Instantiate a command line program oApp := ()
 //Program name  = "GoTool"
 //Description of the application of the program  = "To save the world"
 //Program version number  = "1.0.0"
 
 //Set multiple command processing functions  = []{
 {
 //The full name of the command Name:"lang",
 //Abbreviation of the command Aliases:[]string{"l"},
 //Detailed description of the command Usage:"Setting language",
 //Command processing function Action: func(c *) {
 // Get command line parameters through().First() ("language=%v \n",().First())
 },
 },
 {
 Name:"encode",
 Aliases:[]string{"e"},
 Usage:"Setting encoding",
 Action: func(c *) {
 ("encoding=%v \n",().First())
 },
 },
 }
 
 //start up if err := (); err != nil {
 (err)
 }
 
 /*
 [root@localhost cli]# go run  l english
 language=english 
 
 [root@localhost cli]# go run  e utf8
 encoding=utf8 
 
 [root@localhost cli]# go run  help
 NAME:
 GoTool - To save the world
 
 USAGE:
 main [global options] command [command options] [arguments...]
 
 VERSION:
 1.0.0
 
 COMMANDS:
 lang, l Setting language
 encode, e Setting encoding
 help, h Shows a list of commands or help for one command
 
 GLOBAL OPTIONS:
 --help, -h  show help
 --version, -v print the version
 */ 
}

The above code only implements two simple commands. The last processing functions of the two commands are different. Naturally, different commands are used, and the final output is also different.

Supplement: Go language command line library - urfave/cli (/urfave/cli.v2)

Go language command line library -urfave/cli

Official website:/urfave/cli

Many command-line programs written in Go use the urfave/cli library. urfave/cli is a command line framework.

People who have written command line programs in C should be familiar with it. We need to parse command line parameters one by one according to argc/argv, call different functions, and finally write a usage() function to print help information. urfave/cli encapsulates this process and abstracts the modules such as flag/command/subcommand. Users only need to provide some module configurations, and the parsing and association of parameters are completed within the library, and the help information can also be automatically generated.

Overall, the urfave/cli library is still very useful and has completed a lot of routine work. Programmers only need to focus on the implementation of specific business logic.

How to use urfave/cli

How to write a command line (cli) program

First download the class library package

go get /urfave/cli

package main
import (
 "os"
 "/urfave/cli/v2"
 "fmt"
)
func main() {
 app := &{
 Name: "greet",
 Usage: "say a greeting",
 Action: func(c *) error {
 ("Greetings")
 return nil
 },
 }
 // Accept the starter program ()
}

Flags is used to set parameters.

The corresponding function of Action is your specific processing logic for each parameter.

"/urfave/cli.v2" and "/urfave/cli"

Official website:/urfave/cli

gopkg: a convenient way to manage go pakcage

According to the official website readme description, there are now 2 versions, and the main version uses the v2 branch.

The import package is: "/urfave/cli/v2"

Some go codebase addresses start with, such as /urfave/cli.v2.

v2 indicates that the version number is v2, and the code is the corresponding v2 branch above github.

This is also one of Go's package management solutions, which is to do a forwarding process, which actually uses the corresponding tag code in github

Subcommands

As shown in the demo below, we will add the Action: We can define the pointer & variables in the same layer.

demo:

var daemonStopCmd = &{
 Name: "stop",
 Usage: "Stop a running lotus daemon",
 Flags: []{},
 Action: func(cctx *) error {
 panic("wombat attack")
 },
}
func main() {
 app := &{
 Name: "greet",
 Usage: "say a greeting",
 Action: func(c *) error {
 ("Greetings")
 return nil
 },
 Subcommands: []*{
 daemonStopCmd,
 },
 }
 // Accept the starter program ()
}

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.