...

Source file src/go.opencensus.io/examples/grpc/helloworld_client/main.go

Documentation: go.opencensus.io/examples/grpc/helloworld_client

     1  // Copyright 2017, OpenCensus Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package main
    16  
    17  import (
    18  	"context"
    19  	"log"
    20  	"os"
    21  	"time"
    22  
    23  	"go.opencensus.io/examples/exporter"
    24  	pb "go.opencensus.io/examples/grpc/proto"
    25  	"go.opencensus.io/plugin/ocgrpc"
    26  	"go.opencensus.io/stats/view"
    27  	"google.golang.org/grpc"
    28  )
    29  
    30  const (
    31  	address     = "localhost:50051"
    32  	defaultName = "world"
    33  )
    34  
    35  func main() {
    36  	// Register stats and trace exporters to export
    37  	// the collected data.
    38  	view.RegisterExporter(&exporter.PrintExporter{})
    39  
    40  	// Register the view to collect gRPC client stats.
    41  	if err := view.Register(ocgrpc.DefaultClientViews...); err != nil {
    42  		log.Fatal(err)
    43  	}
    44  
    45  	// Set up a connection to the server with the OpenCensus
    46  	// stats handler to enable stats and tracing.
    47  	conn, err := grpc.Dial(address, grpc.WithStatsHandler(&ocgrpc.ClientHandler{}), grpc.WithInsecure())
    48  	if err != nil {
    49  		log.Fatalf("Cannot connect: %v", err)
    50  	}
    51  	defer conn.Close()
    52  	c := pb.NewGreeterClient(conn)
    53  
    54  	// Contact the server and print out its response.
    55  	name := defaultName
    56  	if len(os.Args) > 1 {
    57  		name = os.Args[1]
    58  	}
    59  	view.SetReportingPeriod(time.Second)
    60  	for {
    61  		r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name})
    62  		if err != nil {
    63  			log.Printf("Could not greet: %v", err)
    64  		} else {
    65  			log.Printf("Greeting: %s", r.Message)
    66  		}
    67  		time.Sleep(2 * time.Second)
    68  	}
    69  }
    70  

View as plain text