Create a gRPC client in Go by defining the service interface, generating client code with protoc, and using the generated client to make requests.
- Install the protocol buffer compiler and Go plugins:
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest && go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest. - Run the compiler to generate Go code from your
.protofile:protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative your_service.proto. - Create a client connection and call the service method in your Go code:
conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := pb.NewYourServiceClient(conn)
resp, err := c.YourMethod(ctx, &pb.YourRequest{})