← Docs
Recipe

gRPC service + handler writer

Generate a complete gRPC service definition and handler scaffold from a protobuf spec.

Prerequisites

  • protoc installed and on PATH
  • protoc-gen-go and protoc-gen-go-grpc plugins
  • A .proto file defining your service

Step 1 — Define the proto

syntax = "proto3";
package orders.v1;
option go_package = "gen/orders/v1;ordersv1";

service OrderService {
  rpc CreateOrder(CreateOrderRequest)
    returns (CreateOrderResponse);
}

message CreateOrderRequest {
  string item_id = 1;
  int32 quantity = 2;
}

message CreateOrderResponse {
  string order_id = 1;
}

Step 2 — Generate stubs

protoc --go_out=. --go-grpc_out=. orders/v1/orders.proto

Step 3 — Write the handler

type OrderServer struct {
  ordersv1.UnimplementedOrderServiceServer
}

func (s *OrderServer) CreateOrder(
  ctx context.Context,
  req *ordersv1.CreateOrderRequest,
) (*ordersv1.CreateOrderResponse, error) {
  id := uuid.New().String()
  return &ordersv1.CreateOrderResponse{
    OrderId: id,
  }, nil
}

Step 4 — Wire the server

lis, _ := net.Listen("tcp", ":50051")
s := grpc.NewServer()
ordersv1.RegisterOrderServiceServer(s, &OrderServer{})
s.Serve(lis)

Tip: Use buf for linting and breaking-change detection in CI.