Stage 3 · Build
API Design & gRPC
gRPC Services
Build unary and streaming RPCs with grpc-go, interceptors, deadlines, reflection, and grpcurl.
gRPC Overview
gRPC is a high-performance RPC framework built on HTTP/2 and Protocol Buffers. It supports unary (request-response) and streaming RPCs. gRPC is ideal for service-to-service communication where performance and type safety matter.
Defining Services
syntax = "proto3";
package user.v1;
service UserService {
rpc GetUser(GetUserRequest) returns (GetUserResponse);
rpc ListUsers(ListUsersRequest) returns (ListUsersResponse);
rpc CreateUser(CreateUserRequest) returns (CreateUserResponse);
rpc SubscribeToChanges(SubscribeRequest) returns (stream UserEvent);
}
message GetUserRequest {
string user_id = 1;
}
message GetUserResponse {
User user = 1;
}
message ListUsersRequest {
int32 page_size = 1;
string page_token = 2;
}
message ListUsersResponse {
repeated User users = 1;
string next_page_token = 2;
}
message CreateUserRequest {
string email = 1;
string name = 2;
string password = 3;
}
message CreateUserResponse {
User user = 1;
}Each rpc method defines a request and response type. Streaming RPCs use the stream keyword. The proto compiler generates Go interfaces and types.
Implementing RPCs
Interceptors
Interceptors are the gRPC equivalent of HTTP middleware. Unary interceptors handle request-response RPCs. Stream interceptors handle streaming RPCs.
Deadlines
Deadlines tell the server how long to process a request. If the server does not respond within the deadline, the client gets a deadline exceeded error. Deadlines prevent cascading failures.
grpcurl
# List services
grpcurl -plaintext localhost:50051 list
# List methods
grpcurl -plaintext localhost:50051 list user.v1.UserService
# Call a method
grpcurl -plaintext -d '{"user_id": "123"}' \
localhost:50051 user.v1.UserService/GetUser
# With authentication
grpcurl -plaintext -H "Authorization: Bearer token123" \
-d '{"email": "alice@example.com"}' \
localhost:50051 user.v1.UserService/CreateUsergrpcurl is curl for gRPC. It discovers services via reflection, constructs requests from proto definitions, and sends them over gRPC. Essential for debugging.
Import grpc reflection package and call reflection.Register(srv). This lets grpcurl discover your services without proto files. Disable it in production.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.