Introduction
In most scenarios, we manage single or multiple commands using the Command
command line object, and the default command line parsing rules (without explicitly using the Parser
parser) are sufficient. The Command
object is defined as follows:
For detailed information, refer to the interface documentation: https://pkg.go.dev/github.com/gogf/gf/v2/os/gcmd@master#Command
// Command holds the info about an argument that can handle custom logic.
type Command struct {
Name string // Command name(case-sensitive).
Usage string // A brief line description about its usage, eg: gf build main.go [OPTION]
Brief string // A brief info that describes what this command will do.
Description string // A detailed description.
Arguments []Argument // Argument array, configuring how this command act.
Func Function // Custom function.
FuncWithValue FuncWithValue // Custom function with output parameters that can interact with command caller.
HelpFunc Function // Custom help function
Examples string // Usage examples.
Additional string // Additional info about this command, which will be appended to the end of help info.
Strict bool // Strict parsing options, which means it returns error if invalid option given.
Config string // Config node name, which also retrieves the values from config component along with command line.
parent *Command // Parent command for internal usage.
commands []*Command // Sub commands of this command.
}
As each object has detailed comments, we will not elaborate further here.
Callback Methods
The Command
object supports 3
callback methods:
Func
: We usually customize this callback method to implement the command execution operation.FuncWithValue
: Method similar toFunc
, but supports return values, often used in scenarios where command lines call each other. Typically not needed in general projects.HelpFunc
: Custom help information. Generally unnecessary, as theCommand
object can automatically generate help information.
We focus mainly on the Func
callback method. Other methods can be explored if interested.
Func
Callback
Method definition:
// Function is a custom command callback function that is bound to a certain argument.
type Function func(ctx context.Context, parser *Parser) (err error)
As seen, within the callback method, we use the parser
object to obtain parsing parameters and options and return error
to inform the upper-level calling method whether the execution was successful.
Example usage:
package main
import (
"context"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/gogf/gf/v2/os/gcmd"
"github.com/gogf/gf/v2/os/gctx"
)
var (
Main = &gcmd.Command{
Name: "main",
Brief: "start http server",
Description: "this is the command entry for starting your http server",
Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
s := g.Server()
s.BindHandler("/", func(r *ghttp.Request) {
r.Response.Write("Hello world")
})
s.SetPort(8199)
s.Run()
return
},
}
)
func main() {
Main.Run(gctx.New())
}
This is what most projects’ command line objects for starting up would look like. Most projects have only one entry point and only one callback method implementation.
Help Information Generation
Although the Command
object can customize the HelpFunc
help callback method, the Command
object can automatically generate Help
usage help information. In most scenarios, customization is unnecessary. Moreover, the gcmd
component has built-in support for h/help
options by default, so programs using the gcmd
component can automatically generate Help
help information using these two options.
Let’s look at an example. We first build the previous example into a binary main
file using go build main.go
, and then take a quick look at the automatically generated help information when there is only one command:
$ ./main -h
USAGE
main [OPTION]
DESCRIPTION
this is the command entry for starting your http server
Hierarchical Command Management
Parent Commands and Subcommands
A Command
command can add subcommands. When a Command
has subcommands, it becomes a parent command. Subcommands can also add their own subcommands, forming a hierarchical command relationship. Both parent commands and subcommands can have their own callback methods, but in most scenarios, once a Command
becomes a parent command, callback methods often become unnecessary. We typically add subcommands to a Command
using the AddCommand
method:
// AddCommand adds one or more sub-commands to current command.
func (c *Command) AddCommand(commands ...*Command) error
Hierarchical Command Usage Example
Let us demonstrate an example of multi-command management. We will improve the previous example by adding two subcommands.
package main
import (
"context"
"fmt"
"github.com/gogf/gf/v2/os/gcmd"
"github.com/gogf/gf/v2/os/gctx"
)
var (
Main = &gcmd.Command{
Name: "main",
Brief: "start http server",
Description: "this is the command entry for starting your process",
}
Http = &gcmd.Command{
Name: "http",
Brief: "start http server",
Description: "this is the command entry for starting your http server",
Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
fmt.Println("start http server")
return
},
}
Grpc = &gcmd.Command{
Name: "grpc",
Brief: "start grpc server",
Description: "this is the command entry for starting your grpc server",
Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
fmt.Println("start grpc server")
return
},
}
)
func main() {
err := Main.AddCommand(Http, Grpc)
if err != nil {
panic(err)
}
Main.Run(gctx.New())
}
As seen, we use the AddCommand
command to add two subcommands http/grpc
to the main command, used respectively for starting http/grpc
services. When subcommands exist, parent command often has no need for a Func
callback definition, so we removed the Func
definition of the main
command here.
After compilation, let us execute to see the effect:
$ main
USAGE
main COMMAND [OPTION]
COMMAND
http start http server
grpc start grpc server
DESCRIPTION
this is the command entry for starting your process
Using the http
command:
$ main http
start http server
Using the grpc
command:
$ main grpc
start grpc server