Analyzing the Boilerplate
I'm focusing now on the essence of the boilerplate - its purpose is to create a functional microservice in Go and gRPC. It needs to provide a starting point with all the necessary elements, like project structure, configurations, and a basic server setup. I'm visualizing how to streamline that initial setup.
Mapping the Structure
The building blocks are solidifying: project structure, dependency management via go.mod, and the vital role of Protocol Buffers for defining the gRPC interface. It's becoming clearer how the code generation and server implementations should mesh. The configuration aspect needs some more thought, but it's shaping up to be a robust foundation.
Constructing the Layout
I'm now fully immersed in the ideal project layout. The server and client entry points, the internal package holding core logic, and pkg for generated code are all starting to gel in my mind. The Makefile feels like it'll be crucial for automating builds and gRPC code generation. The prerequisites for setup are clear.
Developing the Workflow
The Makefile is now the core. I'm concretely defining targets for proto to generate code, server to run the server, client to test connectivity, and tidy to manage dependencies. I'm focusing on the implementation details now: how the service will inherit from UnimplementedGreeterServiceServer, how I'll handle graceful shutdown in the server, and how the client will establish a connection and make a simple gRPC call. I see these as distinct, critical steps.
Integrating Dockerization
I've added a multi-stage Dockerfile to the setup, using a build stage and a slim, distroless run stage. This keeps the image size manageable. I'm also reviewing the codebase, ensuring a clean directory structure and correct imports with placeholder module names. I've opted to omit interceptors for now, aiming for an easy initial setup, though the structure supports them. My current focus is on building the final output.
Organizing the Output
I'm refining the output of the code generation step. Initially, I thought about placing the generated Go code alongside the .proto files, but I've realized that putting it in a dedicated pkg/api/v1 directory provides cleaner separation. This approach allows other services to easily import the generated structs without needing direct access to the .proto files themselves. Also, I've outlined clear instructions on installing the necessary tools, generating the code, and then running the server and client. This should make the boilerplate highly usable.
This is a production-ready boilerplate structure for a Go microservice using gRPC. It follows the Standard Go Project Layout, separates concerns (proto definition vs. logic), and includes a Makefile and Dockerfile.
Prerequisites
You need the following installed:
- Go (1.20+)
- Protocol Buffers Compiler (
protoc)
- Go Plugins for Protoc:
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
1. Project Structure
Create the directory structure:
my-grpc-service/
├── api/
│ └── proto/
│ └── v1/
│ └── hello.proto # The Contract
├── cmd/
│ ├── server/
│ │ └── main.go # Server Entrypoint
│ └── client/
│ └── main.go # Client Entrypoint (for testing)
├── internal/
│ └── service/
│ └── hello.go # Business Logic
├── pkg/
│ └── api/
│ └── v1/ # Generated Go Code lives here
├── go.mod
├── go.sum
├── Makefile
└── Dockerfile
Initialize the module:
mkdir my-grpc-service && cd my-grpc-service
go mod init github.com/youruser/my-grpc-service
2. The Protocol Buffer Definition
File: api/proto/v1/hello.proto
syntax = "proto3";
package v1;
option go_package = "github.com/youruser/my-grpc-service/pkg/api/v1";
service HelloService {
rpc SayHello (HelloRequest) returns (HelloResponse);
}
message HelloRequest {
string name = 1;
}
message HelloResponse {
string message = 1;
}
3. The Makefile (Automation)
This simplifies code generation and running the app.
File: Makefile
# Variables
PROTO_SRC_DIR := api/proto/v1
PROTO_OUT_DIR := pkg/api/v1
.PHONY: all proto clean run build
all: proto build
# Generate Go code from .proto files
proto:
@mkdir -p $(PROTO_OUT_DIR)
protoc --proto_path=api/proto/v1 \
--go_out=$(PROTO_OUT_DIR) --go_opt=paths=source_relative \
--go-grpc_out=$(PROTO_OUT_DIR) --go-grpc_opt=paths=source_relative \
$(PROTO_SRC_DIR)/*.proto
@echo "Protobuf code generated."
# Tidy up go.mod
tidy:
go mod tidy
# Run the server
run:
go run cmd/server/main.go
# Run the client
client:
go run cmd/client/main.go
# Clean generated files
clean:
rm -rf pkg/api/v1/*.go
Run make proto now to generate the Go stubs. Then run make tidy to download dependencies.
4. Business Logic (Implementation)
File: internal/service/hello.go
package service
import (
"context"
"fmt"
"log"
pb "github.com/youruser/my-grpc-service/pkg/api/v1"
)
// HelloServer implements the HelloServiceServer interface generated by protoc
type HelloServer struct {
pb.UnimplementedHelloServiceServer
}
// NewHelloServer creates a new instance
func NewHelloServer() *HelloServer {
return &HelloServer{}
}
// SayHello is the actual implementation of the RPC
func (s *HelloServer) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloResponse, error) {
log.Printf("Received request from: %s", req.GetName())
return &pb.HelloResponse{
Message: fmt.Sprintf("Hello, %s! Welcome to gRPC.", req.GetName()),
}, nil
}
5. Server Entrypoint
Includes graceful shutdown handling.
File: cmd/server/main.go
package main
import (
"log"
"net"
"os"
"os/signal"
"syscall"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
"github.com/youruser/my-grpc-service/internal/service"
pb "github.com/youruser/my-grpc-service/pkg/api/v1"
)
func main() {
port := ":50051"
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
// Create a new gRPC server
s := grpc.NewServer()
// Register result of the service implementation
pb.RegisterHelloServiceServer(s, service.NewHelloServer())
// Enable reflection (allows tools like Postman or grpcurl to inspect the API)
reflection.Register(s)
log.Printf("Server listening at %v", lis.Addr())
// Run server in a goroutine so we can handle shutdown
go func() {
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}()
// Graceful shutdown
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println("Shutting down server...")
s.GracefulStop()
log.Println("Server stopped")
}
6. Client Entrypoint (For Testing)
File: cmd/client/main.go
package main
import (
"context"
"log"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
pb "github.com/youruser/my-grpc-service/pkg/api/v1"
)
func main() {
addr := "localhost:50051"
// Connect to the server
// Note: Using WithTransportCredentials(insecure.NewCredentials()) because we haven't set up TLS
conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := pb.NewHelloServiceClient(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 from server: %s", r.GetMessage())
}
7. Dockerfile
Multi-stage build to keep the image lightweight.
File: Dockerfile
# Stage 1: Build
FROM golang:1.22-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
# Build the binary
RUN go build -o server cmd/server/main.go
# Stage 2: Run
FROM alpine:latest
WORKDIR /root/
# Copy the compiled binary from the builder stage
COPY --from=builder /app/server .
EXPOSE 50051
CMD ["./server"]
How to Run
-
Install Dependencies & Generate Code:
go mod tidy
make proto
go mod tidy # Run again to pick up imports in generated code
-
Run Server:
make run
Output: Server listening at [::]:50051
-
Run Client (in a new terminal):
make client
Output: Response from server: Hello, Developer! Welcome to gRPC.
-
Run with Docker:
docker build -t my-grpc-service .
docker run -p 50051:50051 my-grpc-service