Golang: gRPC Steps Explained

Step by step guide

High level overview of gRPC

syntax = "proto3";
option go_package = "domain.com/me/takeout"
service Takeouts {
rpc GetDish(DishRequest) returns (DishReply) {}
}message DishRequest {
string dish_name = 1;
int32 dish_id = 2;
int32 dish_special_request = 4;
}message Dish {
string dish_name = 1;
int32 dish_id = 2;
int32 last_cooked = 3;
}
message DishReply {
Dish dish = 1;
}
protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative takeout.proto
type takeoutService struct {
takeouts.UnimplementedTakeoutsServer
}
func (s *takeoutService) GetDish(ctx context.Context), in *takeout.DishRequest) (*takeout.DishReply, error) {   //... some code to get the dish based on DishRequest   d := takeout.Dish{     Dish_name: "General Tso's Chicken",     ... 
}
return &takeout.DishReply{Dish: &d}, nil
}
lis, err := net.Listen("tcp", ":50051")
s := grpc.NewServer() //create gRPC Server
takeout.RegisterGetDishServiceServer(s, &takeoutService{})//register handlerlog.Fatal(s.Serve(lis))
// crash the program is cannot create the server
func setupGrpcConnection(addr string) (*grpc.ClientConn, err) {
return grpc.DialContext(context.background(),
addr,
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithBlock(), //block the function until conn
//established
)
} // a connection will be returned
func getDishServiceClient(conn *grpc.ClientConn) takeout.GetDishServiceClient {
return takeout.NewGetDishServiceClient(conn)//this is from
//generated code
//connection from (1)
}
func getDish(client takeout.GetDishServiceClient, 
u *takeout.DishRequest,) (*takeout.DishReply, error){
return client.GetDish(context.Background(), u)
}
Photo by Almos Bechtold on Unsplash

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store