Formulating the Core Structure
I've been concentrating on the essential elements for the Go gRPC boilerplate. My thinking revolves around the minimal framework needed: server setup, gRPC service definition, error handling, configuration loading, and build process. Right now, I'm focusing on the best directory structure to provide clear separation of concerns.
Developing the Boilerplate's Components
I'm now thinking about the detailed components of the boilerplate. The core elements will revolve around a structured directory. The .proto files will define the API that will be code-generated, including the necessary server and client implementations. I'm focusing on features such as dependency management via go.mod, how to load and handle configuration, how to handle logging (potentially Zap or Logrus), graceful shutdown, and how to create a Dockerfile.
Structuring the Project Layout
I'm presently focusing on the project's physical structure. My design is a standard Go layout. The API will be versioned, thus api/v1/service.proto. The cmd directory houses the server and client entrypoints, and internal contains business logic. Dependency management will leverage go.mod. The Makefile automates code generation, builds, and runtime execution.
Enhancing Error Handling and Docker
I'm now thinking about the finer points. I'm focusing on adding graceful shutdown to the server and a lightweight multi-stage Docker build. I'm also planning to use log/slog for logging, to avoid external dependencies, keeping the boilerplate lightweight. Finally, I've decided to put the generated code in pkg/pb so it is easy to import.
Crafting the Boilerplate's Parts
My current thinking is about the actual content I'll generate for the boilerplate. I'm visualizing the files, starting with go.mod initialization. Then, I'll define the service.proto, the Makefile that can automate the gRPC code generation, and the server implementation. Finally, the main server setup and the Dockerfile will complete the bare bones. The layout, explanations and file order are what I'm iterating on. Next, I'll go through a mental checklist of correctness.
This is a production-ready boilerplate structure for a Go microservice using gRPC. It follows the Standard Go Project Layout, which is widely accepted in the Go community for scalability and maintainability.
Prerequisites
You must have the following installed:
- Go (1.21+)
- Protoc Compiler: Install Guide
- 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
Project Structure
This layout separates configuration, business logic, generated code, and entry points.
my-microservice/
├── api/
│ └── proto/
│ └── v1/
│ └── service.proto # Protocol Buffer definitions
├── cmd/
│ ├── server/
│ │ └── main.go # Entry point for the gRPC server
│ └── client/
│ └── main.go # A dummy client for testing
├── internal/
│ └── service/
│ └── greeter.go # Actual implementation of business logic
├── pkg/
│ └── pb/ # Generated Go code (importable by others)
├── Dockerfile
├── go.mod
├── go.sum
└── Makefile # Automates generation and running
1. Define the API (api/proto/v1/service.proto)
We will define a simple "Greeter" service.
syntax = "proto3";
package v1;
option go_package = "github.com/yourusername/my-microservice/pkg/pb";
service GreeterService {
rpc SayHello (HelloRequest) returns (HelloResponse);
}
message HelloRequest {
string name = 1;
}
message HelloResponse {
string message = 1;
}
2. Initialize Module & Dependencies
Run these commands in your terminal root:
go mod init github.com/yourusername/my-microservice
go get google.golang.org/grpc
go get google.golang.org/protobuf
3. The Makefile
This automates the complex protoc commands.
# Makefile
.PHONY: gen clean run build
gen:
@mkdir -p pkg/pb
protoc --proto_path=api/proto/v1 \
--go_out=pkg/pb --go_opt=paths=source_relative \
--go-grpc_out=pkg/pb --go-grpc_opt=paths=source_relative \
service.proto
clean:
rm -rf pkg/pb/*
run:
go run cmd/server/main.go
client:
go run cmd/client/main.go
build:
go build -o bin/server cmd/server/main.go
Now run make gen to generate the code into pkg/pb.
4. Business Logic Implementation (internal/service/greeter.go)
We keep the logic inside internal so it cannot be imported by external projects, forcing them to use the gRPC API.
package service
import (
"context"
"fmt"
"github.com/yourusername/my-microservice/pkg/pb"
)
// GreeterServer implements the gRPC interface
type GreeterServer struct {
pb.UnimplementedGreeterServiceServer
}
func NewGreeterServer() *GreeterServer {
return &GreeterServer{}
}
func (s *GreeterServer) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloResponse, error) {
return &pb.HelloResponse{
Message: fmt.Sprintf("Hello, %s! Welcome to the microservice.", req.Name),
}, nil
}
5. Server Entrypoint (cmd/server/main.go)
This file handles dependency injection, configuration, and graceful shutdown.
package main
import (
"fmt"
"log"
"log/slog"
"net"
"os"
"os/signal"
"syscall"
"github.com/yourusername/my-microservice/internal/service"
"github.com/yourusername/my-microservice/pkg/pb"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
const port = ":50051"
func main() {
// 1. Setup Logger (Go 1.21+ slog)
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
slog.SetDefault(logger)
// 2. Setup TCP Listener
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
// 3. Create gRPC Server
grpcServer := grpc.NewServer()
// 4. Register Service
greeterService := service.NewGreeterServer()
pb.RegisterGreeterServiceServer(grpcServer, greeterService)
// 5. Enable Reflection (for tools like Postman/gRPCurl)
reflection.Register(grpcServer)
// 6. Graceful Shutdown Logic
go func() {
slog.Info("Starting gRPC server", "port", port)
if err := grpcServer.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}()
// Wait for interrupt signal using a channel
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
slog.Info("Shutting down server...")
grpcServer.GracefulStop()
slog.Info("Server stopped")
}
6. Client Entrypoint (cmd/client/main.go)
A simple tool to verify the server works.
package main
import (
"context"
"log"
"time"
"github.com/yourusername/my-microservice/pkg/pb"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
func main() {
// Connect to server
conn, err := grpc.Dial("localhost:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := pb.NewGreeterServiceClient(conn)
// Contact the server and print out its response.
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
r, err := c.SayHello(ctx, &pb.HelloRequest{Name: "Developer"})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
log.Printf("Response: %s", r.GetMessage())
}
7. Dockerfile
A multi-stage build to ensure a tiny production image.
# Stage 1: Build
FROM golang:1.21-alpine AS builder
WORKDIR /app
COPY . .
RUN go mod download
# Build statically linked binary
RUN CGO_ENABLED=0 GOOS=linux go build -o server cmd/server/main.go
# Stage 2: Run
FROM scratch
COPY --from=builder /app/server /server
EXPOSE 50051
ENTRYPOINT ["/server"]
How to Run
- Generate Code:
make gen
- Run Server:
make run
# Output: {"time":"...", "level":"INFO", "msg":"Starting gRPC server", "port":":50051"}
- Run Client (in new terminal):
make client
# Output: Response: Hello, Developer! Welcome to the microservice.
Why this structure?
api/: Your Proto files are the contract. Keeping them separate allows automated tooling to read them easily.
pkg/pb: Defines the publicly accessible generated code. Other Go microservices in your repo can import this path to communicate with this service.
internal/: Enforces strict boundaries. Code here cannot be imported by other projects, keeping your domain logic private and clean.
cmd/: Separates the "main" application wiring from the actual logic. You might have cmd/server, cmd/worker, cmd/cron, all using the same logic in internal.