Читать книгу Practical Go - Amit Saha - Страница 54
Listing 2.2: Implementation of the main
package
Оглавление// chap2/sub-cmd-arch/main.go package main import ( "errors" "fmt" "github.com/username/chap2/sub-cmd-arch/cmd" "io" "os" ) var errInvalidSubCommand = errors.New("Invalid sub-command specified") func printUsage(w io.Writer) { fmt.Fprintf(w, "Usage: mync [http|grpc] -h\n") cmd.HandleHttp(w, []string{"-h"}) cmd.HandleGrpc(w, []string{"-h"}) } func handleCommand(w io.Writer, args []string) error { var err error if len(args) < 1 { err = errInvalidSubCommand } else { switch args[0] { case "http": err = cmd.HandleHttp(w, args[1:]) case "grpc": err = cmd.HandleGrpc(w, args[1:]) case "-h": printUsage(w) case "-help": printUsage(w) default: err = errInvalidSubCommand } } if errors.Is(err, cmd.ErrNoServerSpecified) || errors.Is(err, errInvalidSubCommand) { fmt.Fprintln(w, err) printUsage(w) } return err } func main() { err := handleCommand(os.Stdout, os.Args[1:]) if err != nil { os.Exit(1) } }
At the top, we are importing the cmd
package, which is a sub-package containing the implementation of the sub-commands. Since we will initialize a module for the application, we specify the absolute import path for the cmd
package. The main()
function calls the handleCommand()
function with all of the arguments specified starting from the second argument:
err := handleCommand(os.Args[1:])
If the handleCommand()
function finds that it has received an empty slice, implying that no command-line arguments were specified, it returns a custom error value:
if len(args) < 1 { err = errInvalidSubCommand }
If command-line arguments were specified, a switch..case
construct is defined to call the appropriate command handler function based on the first element of the slice, args
:
1 If this element is http or grpc, the appropriate handler function is called.
2 If the first element is -h or -help, it calls the printUsage() function.
3 If it matches none of the conditions above, the printUsage() function is called and a custom error value is returned.
The printUsage()
function prints a message first using fmt.Fprintf(w, "Usage: mync [http|grpc] -h\n")
and then calls the sub-command implementations with the argument slice containing onl y "-h"
.
Create a new directory, chap2/sub-cmd-arch
, and initialize a module inside it:
$ mkdir -p chap2/sub-cmd-arch $ cd chap2/sub-cmd-arch $ go mod init github.com/username/chap2/sub-cmd-arch/
Save Listing 2.2 as main.go
in the above directory.
Next let's look at HandleHttp()
function, which handles the http
sub-command (see Listing 2.3).