Lab 05: gRPC Service

Time: 45 minutes | Level: Advanced | Docker: docker run -it --rm golang:1.22-alpine sh

Overview

Build a production-grade gRPC service with Protocol Buffers, unary and server-streaming RPCs, interceptors, metadata, and proper error handling with status codes.


Step 1: Install Tools

# Install protoc (Protocol Buffer compiler)
docker run -it --rm golang:1.22-alpine sh -c "
apk add --no-cache protobuf protobuf-dev curl
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
export PATH=\$PATH:\$(go env GOPATH)/bin
protoc --version
echo 'Tools installed'
"

💡 On macOS: brew install protobuf then go install the plugins.


Step 2: Define the Protobuf Schema

Compile:


Step 3: Implement the gRPC Server


Step 4: Implement the gRPC Client


Step 5: gRPC Interceptors

💡 In production, use google.golang.org/grpc/middleware or go.uber.org/zap + grpc interceptors for structured logging, tracing, and metrics.


Step 6: Status Codes & Error Handling


Step 7: Full Working Example (Single File, No Proto)


Step 8: Capstone — Run gRPC Server + Client

For a runnable demo without protoc:

📸 Verified Output:


Summary

Concept
API
Notes

Unary RPC

func(ctx, req) (resp, error)

Request-response

Server streaming

func(req, stream) error

Server sends multiple messages

Client streaming

func(stream) error

Client sends multiple messages

Bidirectional

func(stream) error

Full duplex

Interceptor

grpc.UnaryServerInterceptor

Auth, logging, metrics

Metadata

metadata.FromIncomingContext

HTTP headers equivalent

Status codes

status.Errorf(codes.NotFound, ...)

Structured errors

Key Takeaways:

  • protobuf schema is the single source of truth — generate, don't handwrite

  • Always embed Unimplemented*Server for forward compatibility

  • Use interceptors for cross-cutting concerns (auth, tracing, logging)

  • Status codes map to HTTP status codes — use them semantically

  • io.EOF on stream.Recv() is normal end-of-stream, not an error

Last updated