The user wants a boilerplate for a microservice using Go and gRPC.
I need to provide a complete, yet minimal, project structure that demonstrates the core concepts:
- Project Structure: Standard Go project layout (cmd, internal, api/proto).
- Protocol Buffers: A
.proto file definition.
- Code Generation: Instructions or a Makefile to generate Go code from
.proto.
- Server Implementation: The actual Go code implementing the gRPC server interface.
- Client Implementation: A simple client to test the server.
- Configuration: Basic environment variable or config file handling.
- Docker: Containerization.
- Dependencies:
go.mod file.
Step-by-Step Plan:
-
Directory Layout: Define a clean structure.
cmd/server: Entry point for the server.
cmd/client: Entry point for the client.
api/proto: Protobuf definitions.
internal/service: The business logic implementation.
internal/generated: Where the generated code goes (often excluded from git, but good to show where it lands).
-
The Protocol Buffer (api/proto/v1/service.proto):
- Define a package.
- Define a service (e.g.,
Greeter).
- Define RPC methods (e.g.,
SayHello).
- Define Request/Response messages.
-
Dependencies (go.mod):
- Need
google.golang.org/grpc, google.golang.org/protobuf, and potentially grpc-go-middleware or standard libraries. I'll keep it simple.
-
Code Generation (Makefile or tools.go):
- Need
protoc.
- Need
protoc-gen-go and protoc-gen-go-grpc.
- I will provide a
Makefile for ease of use.
-
Server Implementation:
internal/service/greeter.go: Struct implementing the generated interface.
cmd/server/main.go:
- Start a TCP listener.
- Create a gRPC server instance.
- Register the service.
- Serve.
-
Client Implementation:
cmd/client/main.go:
- Dial the server (with insecure for boilerplate, but mention security).
- Create a client context.
- Call the method.
- Print result.
-
Docker:
- Multi-stage build is best practice.
- Stage 1: Build the Go binary.
- Stage 2: Scratch or Alpine image running the binary.
-
Refinement:
- Add a
.gitignore.
- Add comments explaining the parts.
- Ensure Go module paths match the directory structure.
Drafting the Content:
-
Structure:
my-grpc-service/
├── api/
│ └── proto/
│ └── v1/
│ └── greeter.proto
├── cmd/
│ ├── client/
│ │ └── main.go
│ └── server/
│ └── main.go
├── internal/
│ └── service/
│ └── greeter.go
├── Makefile
├── Dockerfile
└── go.mod
-
Protobuf:
Standard Greeter example is the "Hello World" of gRPC.
-
Makefile:
Crucial command: protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative api/proto/v1/*.proto. Actually, better to output to a specific folder or keep relative. Relative is easier for a boilerplate.
-
Go Code:
Keep it standard. Use log package. Handle errors.
-
Docker:
Use golang:1.22-alpine as builder.
Self-Correction/Review during drafting:
- Issue: Protobuf generation can be tricky with paths.
- Solution: I will stick to
paths=source_relative and assume the user runs commands from the root.
- Issue: Boilerplates often get bloated.
- Solution: Keep dependencies minimal. No complex DI frameworks, just standard library + grpc libs.
Final Output Generation:
I will present this as a guide with code blocks for each file, followed by instructions on how to run it.
Let's assemble the response.
- Intro: Briefly explain the stack.
- Prerequisites: Go, Protoc.
- Project Structure: The tree view.
- Step 1: Protocol Buffers: The
.proto file.
- Step 2: Dependencies:
go.mod and tools.
- Step 3: Makefile: For generation.
- Step 4: Implementation: Server logic and Main entry points.
- Step 5: Docker: Containerization.
- Step 6: Run Instructions: How to actually use it.
This looks solid. I will implement this structure now.
Here is a complete, production-ready boilerplate for a Go gRPC microservice. It includes a clean project structure, Protocol Buffer definitions, a server implementation, a client implementation, and a Dockerfile.
Prerequisites
To use this boilerplate locally, you need to install:
- Go (1.21+)
- Protobuf Compiler (
protoc)
- Go Plugins for Protobuf:
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
This structure separates your API definitions from your internal business logic.
my-grpc-service/
├── api/
│ └── proto/
│ └── v1/
│ └── greeter.proto # API Definition
├── cmd/
│ ├── client/
│ │ └── main.go # Client entrypoint
│ └── server/
│ └── main.go # Server entrypoint
├── internal/
│ └── service/
│ └── greeter.go # Business Logic Implementation
├── Dockerfile
├── Makefile # Automation scripts
└── go.mod
2. Initialize Module
Create the directory and initialize the go module.
mkdir my-grpc-service
cd my-grpc-service
go mod init github.com/yourusername/my-grpc-service
3. The Protocol Buffer Definition
Create the file api/proto/v1/greeter.proto.
File: api/proto/v1/greeter.proto
syntax = "proto3";
package v1;
option go_package = "github.com/yourusername/my-grpc-service/gen/go/v1;v1";
// The greeting service definition.
service GreeterService {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
4. The Makefile
To avoid typing long protoc commands, we use a Makefile. Create Makefile in the root.
File: Makefile
.PHONY: clean proto server client
# 1. Generate Protobuf Go code
proto:
@echo "Generating Proto..."
@mkdir -p gen/go/v1
protoc api/proto/v1/*.proto \
--go_out=gen/go/v1 \
--go_opt=paths=source_relative \
--go-grpc_out=gen/go/v1 \
--go-grpc_opt=paths=source_relative
# 2. Clean generated files
clean:
@echo "Cleaning..."
@rm -rf gen/
# 3. Run Server
server:
@go run cmd/server/main.go
# 4. Run Client
client:
@go run cmd/client/main.go
5. Generate Code
Run the make command to generate the Go gRPC server/client stubs.
make proto
This will create a folder gen/go/v1/ containing .pb.go files.
Now, tidy your dependencies:
go mod tidy
6. Server Implementation
We implement the interface generated by Protobuf.
File: internal/service/greeter.go
package service
import (
"context"
v1 "github.com/yourusername/my-grpc-service/gen/go/v1"
)
// GreeterService implements the v1.GreeterServiceServer interface
type GreeterService struct {
v1.UnimplementedGreeterServiceServer
}
// NewGreeterService creates a new service instance
func NewGreeterService() *GreeterService {
return &GreeterService{}
}
// SayHello implements the SayHello RPC method
func (s *GreeterService) SayHello(ctx context.Context, req *v1.HelloRequest) (*v1.HelloReply, error) {
// Here is where your business logic lives
return &v1.HelloReply{
Message: "Hello " + req.GetName(),
}, nil
}
File: cmd/server/main.go
package main
import (
"log"
"net"
"google.golang.org/grpc"
v1 "github.com/yourusername/my-grpc-service/gen/go/v1"
"github.com/yourusername/my-grpc-service/internal/service"
)
func main() {
// 1. Create a listener on TCP port 50051
lis, err := net.Listen("tcp", ":50051")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
// 2. Create a new gRPC server instance
grpcServer := grpc.NewServer()
// 3. Register our service implementation
greeterSvc := service.NewGreeterService()
v1.RegisterGreeterServiceServer(grpcServer, greeterSvc)
// 4. Start serving
log.Println("Server listening on :50051")
if err := grpcServer.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
7. Client Implementation
A simple client to test the endpoint.
File: cmd/client/main.go
package main
import (
"context"
"log"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
v1 "github.com/yourusername/my-grpc-service/gen/go/v1"
)
func main() {
// 1. Connect to the server
conn, err := grpc.Dial("localhost:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
// 2. Create a client
client := v1.NewGreeterServiceClient(conn)
// 3. Call the RPC
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
response, err := client.SayHello(ctx, &v1.HelloRequest{Name: "World"})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
log.Printf("Server Response: %s", response.GetMessage())
}
8. Dockerfile (Multi-stage)
This creates a minimal container image for your service.
File: Dockerfile
# Stage 1: Build
FROM golang:1.22-alpine AS builder
WORKDIR /app
# Copy go mod files
COPY go.mod go.sum ./
RUN go mod download
# Copy source code
COPY . .
# Build the binary
# CGO_ENABLED=0 is important for static linking in scratch/distroless images
RUN CGO_ENABLED=0 GOOS=linux go build -o /grpc-server ./cmd/server
# Stage 2: Run
FROM alpine:latest
WORKDIR /app
# Copy binary from builder
COPY --from=builder /grpc-server .
# Expose port
EXPOSE 50051
# Run
CMD ["./grpc-server"]
9. How to Run
1. Run the Server
Open a terminal window:
make server
# Output: Server listening on :50051
2. Run the Client
Open a second terminal window:
make client
# Output: Server Response: Hello World
3. Build Docker Image
docker build -t my-grpc-service .
docker run -p 50051:50051 my-grpc-service