This guide gets you started with gRPC in Go with a simple working example.
Prerequisites
Get the example code
The example code is part of the grpc-go repo.
$ git clone -b v1.50.0 --depth 1 https://github.com/grpc/grpc-go
$ cd grpc-go/examples/helloworld
Run the example
examples/helloworld
$ go run greeter_server/main.go
$ go run greeter_client/main.go
Greeting: Hello world
Congratulations! You’ve just run a client-server application with gRPC.
Update the gRPC service
.protoSayHello()HelloRequestHelloReply
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
helloworld/helloworld.protoSayHelloAgain()
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
// Sends another greeting
rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
Remember to save the file!
Regenerate gRPC code
.proto
examples/helloworld
$ protoc --go_out=. --go_opt=paths=source_relative \
--go-grpc_out=. --go-grpc_opt=paths=source_relative \
helloworld/helloworld.proto
helloworld/helloworld.pb.gohelloworld/helloworld_grpc.pb.go
HelloRequestHelloReply
Update and run the application
You have regenerated server and client code, but you still need to implement and call the new method in the human-written parts of the example application.
Update the server
greeter_server/main.go
func (s *server) SayHelloAgain(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
return &pb.HelloReply{Message: "Hello again " + in.GetName()}, nil
}
Update the client
greeter_client/main.gomain()
r, err = c.SayHelloAgain(ctx, &pb.HelloRequest{Name: *name})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
log.Printf("Greeting: %s", r.GetMessage())
Remember to save your changes.
Run!
examples/helloworld
$ go run greeter_server/main.go
$ go run greeter_client/main.go --name=Alice
Greeting: Hello Alice
Greeting: Hello again Alice