Читать книгу Practical Go - Amit Saha - Страница 52

Listing 2.1: Implementing sub-commands in a command-line application

Оглавление

// chap2/sub-cmd-example/main.go package main import ( "flag" "fmt" "io" "os" ) // TODO Insert handleCmdaA() implementation as earlier func handleCmdB(w io.Writer, args []string) error { var v string fs := flag.NewFlagSet("cmd-b", flag.ContinueOnError) fs.SetOutput(w) fs.StringVar(&v, "verb", "argument-value", "Argument 1") err := fs.Parse(args) if err != nil { return err } fmt.Fprintf(w, "Executing command B") return nil } // TODO Insert printUsage() implementation as earlier func main() { var err error if len(os.Args) < 2 { printUsage(os.Stdout) os.Exit(1) } switch os.Args[1] { case "cmd-a": err = handleCmdA(os.Stdout, os.Args[2:]) case "cmd-b": err = handleCmdB(os.Stdout, os.Args[2:]) default: printUsage(os.Stdout) } if err != nil { fmt.Fprintln(os.Stdout, err) os.Exit(1) } }

Create a new directory chap2/sub-cmd-example/, and initialize a module inside it:

$ mkdir -p chap2/sub-cmd-example $ cd chap2/sub-cmd-example $ go mod init github.com/username/sub-cmd-example

Next, save Listing 2.1 as a file main.go within it. Build and run the application without any arguments:

$ go build -o application $ ./application Usage: ./application [cmd-a|cmd-b] -h Usage of cmd-a: -verb string Argument 1 (default "argument-value") Usage of cmd-b: -verb string Argument 1 (default "argument-value")

Try executing any of the sub-commands:

$ ./application cmd-a Executing command A $ ./application cmd-b Executing command B

You have now seen an example of how you can implement your command-line application with sub-commands by creating multiple FlagSet objects. Each sub-command is constructed like a stand-alone command-line application. Thus, implementing sub-commands is a great way to separate unrelated functionalities of your application. For example, the go build sub-command provides all of the build-related functionality and the go test sub-command provides all of the testing-related functionality for a Go project.

Let's continue this exploration by discussing a strategy to make this scalable.

Practical Go

Подняться наверх