I'm focusing on building a boilerplate template for a microservice using Go and gRPC. Even though the user didn't specify a domain, I’ll create a usable template that includes folder structure, go.mod, proto file, server, client, main, and possibly a Makefile with clear instructions and code snippets.
For the service, I might define a "UserService" featuring operations like GetUser and CreateUser. I'll include essential aspects like health checks, logging, and graceful shutdowns in the structure as well.Outlining a Go microservice
I need to create a concise, yet production-ready skeleton for a microservice using gRPC. I’ll focus on keeping it lean while still being helpful. My plan includes outlining the project structure, providing a proto file, server code, main file, and basic client code, along with build/run instructions.
I'll ensure to include configurations via environment variables and implement graceful shutdown with context and OS signals. Additionally, I'll use gRPC version 1.66 and follow best practices while being concise.Defining gRPC Proto and Implementation
For the gRPC service, I’ll define messages like CreateUser, GetUser, and possibly ListUsers. The service, UserService, will have methods for GetUser and CreateUser. I’ll keep it straightforward by using proto syntax version 3, with appropriate package options.
To generate the code, I'll provide the command to use protoc, noting that they should have the necessary plugins installed. For the implementation, I’ll create an interface in service.go to define the methods, then directly implement the UserServiceServer. I'll include a simple in-memory repository for completeness and set up the gRPC server with logging and health checks.Finalizing main.go and Testing
In main.go, I’ll set up everything needed to run the microservice, including parsing environment configurations like PORT, initializing the logger, creating the repository, and starting the server while handling OS signals.
For testing, I’ll provide a small snippet of a client using grpcurl since it’s straightforward for testing gRPC services. While I won't duplicate entire files loaded with comments, I'll ensure the code compiles and that import paths remain consistent. I'll also include placeholders where necessary and maintain the correct proto go_package reference.Structuring the Boilerplate
I’ll briefly mention including a Makefile for generating proto files, but I want to keep things concise. Instead, I’ll provide clear instructions for creating the project structure, writing the proto file, generating the necessary files, and running the service.
I plan to present the entire minimal code set along with short run instructions, ensuring no extraneous explanations creep in. I’ll structure the answer to include the project layout, contents of essential files, generation commands, and testing commands, while reminding the user to replace the module path with their own. I'll double-check the imports to ensure everything is tidy. Below is a minimal but realistic boilerplate for a Go microservice using gRPC, including:
Project layout
A sample .proto
Service implementation
gRPC server setup with logging, health check, reflection
Main entrypoint
Proto generation and run instructions
Adjust the module path (github.com/example/usersvc) to your own.
1. Project layout
text
usersvc/
├── api
│ ├── gen # Generated code (protoc output)
│ │ └── user
│ │ └── v1
│ └── proto # .proto definitions (source of truth)
│ └── user
│ └── v1
│ └── user.proto
├── cmd
│ └── usersvc
│ └── main.go # Service entrypoint
├── internal
│ ├── server
│ │ └── grpc.go # gRPC server wiring
│ └── user
│ └── service.go # Business logic / gRPC handlers
├── go.mod
└── go.sum
package user
import (
"context"
"fmt"
"sync"
userv1 "github.com/example/usersvc/api/gen/user/v1"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// UserService implements the generated gRPC interface.
type UserService struct {
userv1.UnimplementedUserServiceServer
mu sync.RWMutex
users map[string]*userv1.User
idSeq int64
}
func NewUserService() *UserService {
return &UserService{
users: make(map[string]*userv1.User),
}
}
func (s *UserService) GetUser(
ctx context.Context,
req *userv1.GetUserRequest,
) (*userv1.GetUserResponse, error) {
s.mu.RLock()
defer s.mu.RUnlock()
user, ok := s.users[req.GetId()]
if !ok {
return nil, status.Errorf(codes.NotFound, "user %s not found", req.GetId())
}
return &userv1.GetUserResponse{
User: user,
}, nil
}
func (s *UserService) CreateUser(
ctx context.Context,
req *userv1.CreateUserRequest,
) (*userv1.CreateUserResponse, error) {
if req.GetName() == "" || req.GetEmail() == "" {
return nil, status.Error(codes.InvalidArgument, "name and email are required")
}
s.mu.Lock()
defer s.mu.Unlock()
s.idSeq++
id := fmt.Sprintf("%d", s.idSeq)
user := &userv1.User{
Id: id,
Name: req.GetName(),
Email: req.GetEmail(),
}
s.users[id] = user
return &userv1.CreateUserResponse{
User: user,
}, nil
}
6. gRPC server wiring
File:internal/server/grpc.go
go
package server
import (
"context"
"log"
"net"
"time"
userv1 "github.com/example/usersvc/api/gen/user/v1"
"google.golang.org/grpc"
"google.golang.org/grpc/health"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/reflection"
)
// NewGRPCServer configures a gRPC server with logging, health, reflection.
func NewGRPCServer(userSvc userv1.UserServiceServer) *grpc.Server {
unaryInterceptor := func(
ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler,
) (interface{}, error) {
start := time.Now()
var addr string
if p, ok := peer.FromContext(ctx); ok && p.Addr != nil {
addr = p.Addr.String()
}
resp, err := handler(ctx, req)
log.Printf(
"method=%s peer=%s duration=%s err=%v",
info.FullMethod, addr, time.Since(start), err,
)
return resp, err
}
s := grpc.NewServer(
grpc.UnaryInterceptor(unaryInterceptor),
)
// Register application service
userv1.RegisterUserServiceServer(s, userSvc)
// Health check
hs := health.NewServer()
hs.SetServingStatus("", healthpb.HealthCheckResponse_SERVING)
healthpb.RegisterHealthServer(s, hs)
// Reflection (useful for grpcurl / debugging)
reflection.Register(s)
return s
}
// RunGRPCServer starts the gRPC server and listens for ctx cancellation to stop.
func RunGRPCServer(ctx context.Context, addr string, srv *grpc.Server) error {
lis, err := net.Listen("tcp", addr)
if err != nil {
return err
}
// Shutdown on context cancellation
go func() {
<-ctx.Done()
log.Println("shutting down gRPC server...")
srv.GracefulStop()
}()
log.Printf("gRPC server listening on %s", addr)
if err := srv.Serve(lis); err != nil {
// ErrServerStopped is returned after GracefulStop; treat as clean exit.
if err == grpc.ErrServerStopped {
return nil
}
return err
}
return nil
}
7. Entrypoint
File:cmd/usersvc/main.go
go
package main
import (
"context"
"log"
"os"
"os/signal"
"syscall"
"github.com/example/usersvc/internal/server"
"github.com/example/usersvc/internal/user"
)
func main() {
addr := ":50051"
if v := os.Getenv("GRPC_ADDR"); v != "" {
addr = v
}
// Context cancelled on SIGINT / SIGTERM
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
userSvc := user.NewUserService()
grpcServer := server.NewGRPCServer(userSvc)
if err := server.RunGRPCServer(ctx, addr, grpcServer); err != nil {
log.Fatalf("server error: %v", err)
}
log.Println("server exited cleanly")
}
8. Run & test
From project root:
bash
# Generate proto (if not already done)
protoc \
-I api/proto \
--go_out=api/gen --go_opt=paths=source_relative \
--go-grpc_out=api/gen --go-grpc_opt=paths=source_relative \
api/proto/user/v1/user.proto
# Build
go build ./cmd/usersvc
# Or run directly
go run ./cmd/usersvc
The service listens on :50051 by default (override via GRPC_ADDR).
Using grpcurl to test
Install grpcurl if needed, then:
bash
# List services
grpcurl -plaintext localhost:50051 list
# List methods for UserService
grpcurl -plaintext localhost:50051 list user.v1.UserService
# Create a user
grpcurl -plaintext -d '{"name": "Alice", "email": "alice@example.com"}' \
localhost:50051 user.v1.UserService/CreateUser
# Suppose the returned id is "1", fetch it:
grpcurl -plaintext -d '{"id": "1"}' \
localhost:50051 user.v1.UserService/GetUser
# Health check
grpcurl -plaintext localhost:50051 grpc.health.v1.Health/Check
If you’d like, I can extend this boilerplate with: