create a cli to connect grpc in go

To create a CLI to connect to gRPC in Go, follow these steps:

  1. Define your protobuf service:
syntax = "proto3";

package greetings;

service HelloWorld {
  rpc SayHello (HelloRequest) returns (HelloResponse) {}
}

message HelloRequest {
  string name = 1;
}

message HelloResponse {
  string message = 1;
}
214 chars
16 lines
  1. Generate the Go code from the protobuf definition. To generate the code, you need to run:
main.go
$ protoc --go_out=plugins=grpc:. hello.proto
45 chars
2 lines

This will generate the hello.pb.go file.

  1. Create a main.go file and import the necessary packages:
main.go
package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"os"
	"time"

	"google.golang.org/grpc"
	"github.com/user/greetings"
)
128 chars
14 lines
  1. Parse the command line arguments using the flag package:
main.go
var name = flag.String("name", "world", "name to greet")
var address = flag.String("address", ":8080", "gRPC server address")
126 chars
3 lines
  1. Initialize the gRPC connection:
main.go
conn, err := grpc.Dial(*address, grpc.WithInsecure(), grpc.WithBlock())
if err != nil {
    log.Fatalf("could not connect: %v", err)
}
defer conn.Close()

c := greetings.NewHelloWorldClient(conn)
196 chars
8 lines
  1. Build the request and call the function:
main.go
req := &greetings.HelloRequest{
    Name: *name,
}

ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()

r, err := c.SayHello(ctx, req)
if err != nil {
    log.Fatalf("could not greet: %v", err)
}

fmt.Printf("Greeting: %s\n", r.Message)
271 chars
14 lines

This will create a client to connect to the gRPC server and make a request.

  1. Build the binary and test the CLI:
main.go
$ go build -o helloworld
$ ./helloworld --name=test --address=localhost:8080
Greeting: Hello test
98 chars
4 lines

You can now use this CLI to connect to any gRPC server that implements the defined service.

gistlibby LogSnag