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

Listing 2.3: Implementation of the HandleHttp() function

Оглавление

// chap2/sub-cmd-arch/cmd/httpCmd.go package cmd import ( "flag" "fmt" "io" ) type httpConfig struct { url string verb string } func HandleHttp(w io.Writer, args []string) error { var v string fs := flag.NewFlagSet("http", flag.ContinueOnError) fs.SetOutput(w) fs.StringVar(&v, "verb", "GET", "HTTP method") fs.Usage = func() { var usageString = ` http: A HTTP client. http: <options> server` fmt.Fprintf(w, usageString) fmt.Fprintln(w) fmt.Fprintln(w) fmt.Fprintln(w, "Options: ") fs.PrintDefaults() } err := fs.Parse(args) if err != nil { return err } if fs.NArg() != 1 { return ErrNoServerSpecified } c := httpConfig{verb: v} c.url = fs.Arg(0) fmt.Fprintln(w, "Executing http command") return nil }

The HandleHttp() function creates a FlagSet object and configures it with an option, a custom usage, and other error handling.

Create a new subdirectory, cmd, inside the directory that you created earlier, and save Listing 2.3 as httpCmd.go .

The HandleGrpc() function is implemented in a similar fashion (see Listing 2.4).

Practical Go

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