Building a microservice boilerplate
The user wants a boilerplate for a microservice using Go and gRPC, which suggests including items like proto files, server implementation, Dockerfile, and Makefile. Although the user didn’t specify too many details, I’m thinking about including a file tree and key file contents while keeping it concise. I need to confirm if we’re using classic gRPC from google.golang.org/grpc, along with the necessary structure and libraries such as logging and configuration management. I'll also mention how to generate files.Creating a boilerplate service
I need to provide a moderate-length answer while acknowledging that the code itself might be long, which is okay. I’m thinking about proposing a minimal service, perhaps called "Greeter" or "UserService," with methods like GetUser and CreateUser. The folder layout could include paths like /cmd/server/main.go, /internal/server/server.go, and /proto/helloworld/helloworld.proto.
I'll consider health checks via grpc-health-probe and decide on using either a buf configuration or sticking with the protoc command for proto file generation. Ultimately, I want to keep things straightforward and step-by-step for the user.Setting up the Go module
I need to make sure the code compiles, so I’m thinking about using a module name like example.com/microservice and advising the user to adjust it accordingly. For the go.mod file, I might start with something like:
module github.com/yourname/hellosvc
go 1.22
require (
google.golang.org/grpc v1.64.0
google.golang.org/protobuf v1.35.1
)
However, I’m unsure about the latest tags. It's safer to suggest they run go get google.golang.org/grpc@latest instead of hard-coding versions. I could just provide instructions for initializing the module and getting the necessary packages, guiding them while avoiding stale version issues.Creating the code snippet
For the code snippet, it's okay to use a placeholder like vX.Y.Z that the user can eventually replace. I could also add a comment like // latest to clarify.
Now, I want to base it on approximate versions as of October 2024. Since gRPC was at v1.62 in April 2024, I can reasonably guess it might reach v1.66 by October. However, I'll play it safe and just use a placeholder version string.
In my response, I'll use Markdown formatting with headings and code fences. I’ll include the .proto definition, setting the go_package option to guide the user. The service will be simplified to just a rpc SayHello(HelloRequest) returns (HelloReply) {} structure. I'll also ensure to address status errors using the necessary imports, while mentioning that the generated helloworld_grpc.pb.go will produce a server interface for the GreeterServer.Designing the file structure
Here’s a minimal but realistic boilerplate file structure for a Go microservice using gRPC:
.
├── cmd/server/main.go
├── internal/greeter/service.go
├── proto/helloworld.proto
├── gen/... (generated code)
├── go.mod
└── Makefile
In main.go, I’ll set up the server, including context for graceful shutdown and a basic logging unary interceptor. I can mention generating the necessary code with the protoc command. The Makefile will handle the protocol buffer compilation and running the server, ensuring that the user installs required dependencies like protoc-gen-go. I’ll provide snippets for the relevant files with brief explanations, keeping it straightforward. Here’s a minimal but realistic boilerplate for a Go microservice using gRPC.
1. Project layout
your-service/
├── cmd/
│ └── server/
│ └── main.go
├── internal/
│ └── greeter/
│ └── service.go
├── proto/
│ └── helloworld.proto
├── gen/ # generated code (do NOT edit)
├── go.mod
└── Makefile
2. go.mod
Run this once in the project root:
go mod init github.com/yourname/your-service
go get google.golang.org/grpc@latest
go get google.golang.org/protobuf@latest
Resulting go.mod will look something like:
module github.com/yourname/your-service
go 1.22
require (
google.golang.org/grpc vX.Y.Z
google.golang.org/protobuf vA.B.C
)
(Exact versions will be filled by go get.)
3. Protobuf definition – proto/helloworld.proto
syntax = "proto3";
package helloworld.v1;
option go_package = "github.com/yourname/your-service/gen/helloworld/v1;helloworldv1";
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
service Greeter {
rpc SayHello(HelloRequest) returns (HelloReply);
}
Update the go_package path to your module path.
4. Code generation setup
4.1 Install protoc plugins
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
Make sure $GOPATH/bin (or wherever Go installs binaries) is in your $PATH.
4.2 Makefile – Makefile
PROTO_DIR = proto
GEN_DIR = gen
.PHONY: proto run
proto:
protoc -I=$(PROTO_DIR) \
--go_out=$(GEN_DIR) --go_opt=paths=source_relative \
--go-grpc_out=$(GEN_DIR) --go-grpc_opt=paths=source_relative \
$(PROTO_DIR)/helloworld.proto
run:
go run ./cmd/server
Generate the gRPC code:
make proto
This will create gen/helloworld/v1/helloworld.pb.go and helloworld_grpc.pb.go.
5. Service implementation – internal/greeter/service.go
package greeter
import (
"context"
"fmt"
"strings"
helloworldv1 "github.com/yourname/your-service/gen/helloworld/v1"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type Service struct {
helloworldv1.UnimplementedGreeterServer
}
func New() *Service {
return &Service{}
}
func (s *Service) SayHello(
ctx context.Context,
req *helloworldv1.HelloRequest,
) (*helloworldv1.HelloReply, error) {
name := strings.TrimSpace(req.GetName())
if name == "" {
return nil, status.Error(codes.InvalidArgument, "name is required")
}
msg := fmt.Sprintf("Hello, %s!", name)
return &helloworldv1.HelloReply{Message: msg}, nil
}
6. gRPC server entrypoint – cmd/server/main.go
package main
import (
"context"
"fmt"
"log"
"net"
"os"
"os/signal"
"syscall"
"time"
"github.com/yourname/your-service/internal/greeter"
helloworldv1 "github.com/yourname/your-service/gen/helloworld/v1"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
func main() {
// Context that is cancelled on SIGINT/SIGTERM
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
port := getEnv("PORT", "50051")
addr := ":" + port
lis, err := net.Listen("tcp", addr)
if err != nil {
log.Fatalf("failed to listen on %s: %v", addr, err)
}
grpcServer := grpc.NewServer(
grpc.UnaryInterceptor(loggingUnaryInterceptor),
)
greeterSvc := greeter.New()
helloworldv1.RegisterGreeterServer(grpcServer, greeterSvc)
// Enable server reflection for tools like grpcurl / Postman
reflection.Register(grpcServer)
log.Printf("gRPC server listening on %s", addr)
// Start serving in a goroutine
go func() {
if serveErr := grpcServer.Serve(lis); serveErr != nil {
log.Printf("gRPC server stopped with error: %v", serveErr)
stop()
}
}()
// Wait for shutdown signal
<-ctx.Done()
log.Println("shutdown signal received")
// Graceful shutdown with timeout
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
ch := make(chan struct{})
go func() {
grpcServer.GracefulStop()
close(ch)
}()
select {
case <-ch:
log.Println("gRPC server stopped gracefully")
case <-shutdownCtx.Done():
log.Println("timeout during graceful shutdown, forcing stop")
grpcServer.Stop()
}
}
func getEnv(key, fallback string) string {
if v := os.Getenv(key); v != "" {
return v
}
return fallback
}
func loggingUnaryInterceptor(
ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler,
) (interface{}, error) {
start := time.Now()
resp, err := handler(ctx, req)
log.Printf("method=%s duration=%s error=%v", info.FullMethod, time.Since(start), err)
return resp, err
}
7. Run the service
# Generate gRPC code
make proto
# Run the server
PORT=50051 make run
# or: PORT=50051 go run ./cmd/server
8. Quick client test (using grpcurl)
grpcurl -plaintext -d '{"name":"World"}' localhost:50051 helloworld.v1.Greeter/SayHello
Expected response:
{
"message": "Hello, World!"
}
If you want, I can add:
- a simple gRPC client in Go,
- Dockerfile + docker-compose,
- or health/readiness check endpoints using
grpc-health-probe.