Читать книгу Practical Go - Amit Saha - Страница 56
Listing 2.4: Implementation of the HandleGrpc()
function
Оглавление// chap2/sub-cmd-arch/cmd/grpcCmd.go package cmd import ( "flag" "fmt" "io" ) type grpcConfig struct { server string method string body string } func HandleGrpc(w io.Writer, args []string) error { c := grpcConfig{} fs := flag.NewFlagSet("grpc", flag.ContinueOnError) fs.SetOutput(w) fs.StringVar(&c.method, "method", "", "Method to call") fs.StringVar(&c.body, "body", "", "Body of request") fs.Usage = func() { var usageString = ` grpc: A gRPC client. grpc: <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.server = fs.Arg(0) fmt.Fprintln(w, "Executing grpc command") return nil }
Save Listing 2.4 as grpcCmd.go
in the cmd
subdirectory.
The custom error value, ErrNoServerSpecified
, is created in a separate file in the cmd
package as shown in Listing 2.5.