github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2015/gotham-grpc/client/client.go (about)

     1  // The client command issues RPCs to a Google server and prints the
     2  // results.
     3  //
     4  // In "search" mode, client calls Search on the server and prints the
     5  // results.
     6  //
     7  // In "watch" mode, client starts a Watch on the server and prints the
     8  // result stream.
     9  package main
    10  
    11  import (
    12  	"flag"
    13  	"fmt"
    14  	"io"
    15  	"log"
    16  	"time"
    17  
    18  	"golang.org/x/net/context"
    19  	pb "golang.org/x/talks/2015/gotham-grpc/search"
    20  	"google.golang.org/grpc"
    21  )
    22  
    23  var (
    24  	server = flag.String("server", "localhost:36060", "server address")
    25  	mode   = flag.String("mode", "search", `one of "search" or "watch"`)
    26  	query  = flag.String("query", "test", "query string")
    27  )
    28  
    29  func main() {
    30  	flag.Parse()
    31  
    32  	// Connect to the server.
    33  	conn, err := grpc.Dial(*server, grpc.WithInsecure()) // HL
    34  	if err != nil {
    35  		log.Fatalf("fail to dial: %v", err)
    36  	}
    37  	defer conn.Close()
    38  	client := pb.NewGoogleClient(conn) // HL
    39  
    40  	// Run the RPC.
    41  	switch *mode {
    42  	case "search":
    43  		search(client, *query) // HL
    44  	case "watch":
    45  		watch(client, *query)
    46  	default:
    47  		log.Fatalf("unknown mode: %q", *mode)
    48  	}
    49  }
    50  
    51  // search issues a search for query and prints the result.
    52  func search(client pb.GoogleClient, query string) {
    53  	ctx, cancel := context.WithTimeout(context.Background(), 80*time.Millisecond) // HL
    54  	defer cancel()
    55  	req := &pb.Request{Query: query}    // HL
    56  	res, err := client.Search(ctx, req) // HL
    57  	if err != nil {
    58  		log.Fatal(err)
    59  	}
    60  	fmt.Println(res) // HL
    61  }
    62  
    63  // watch runs a Watch RPC and prints the result stream.
    64  func watch(client pb.GoogleClient, query string) {
    65  	ctx, cancel := context.WithCancel(context.Background())
    66  	defer cancel()
    67  	req := &pb.Request{Query: query}      // HL
    68  	stream, err := client.Watch(ctx, req) // HL
    69  	if err != nil {
    70  		log.Fatal(err)
    71  	}
    72  	for {
    73  		res, err := stream.Recv() // HL
    74  		if err == io.EOF {        // HL
    75  			fmt.Println("and now your watch is ended")
    76  			return
    77  		}
    78  		if err != nil {
    79  			log.Fatal(err)
    80  		}
    81  		fmt.Println(res) // HL
    82  	}
    83  }