This is a comprehensive request for a Go microservice boilerplate with graceful shutdown handling. I'll create a complete example that includes:
A basic HTTP server
Graceful shutdown handling with signal catching
Database connection management
Active request tracking
Timeout handling
Proper cleanup procedures
Best practices for production-ready code
Let me structure this with multiple files to show a real-world layout:
main.go
server.go
database.go
handlers.go
config.go
middleware.go
logger.go (optional but good for production)
I'll include:
Context usage for cancellation
WaitGroup for tracking active requests
Graceful shutdown with timeouts
Database connection pooling
Signal handling
Structured logging
Error handling
Health check endpoints
Let me create a comprehensive solution:
Go Microservice Boilerplate with Graceful Shutdown
I'll create a production-ready microservice with comprehensive graceful shutdown handling.
Project Structure
code Copy code
microservice/
├── main.go
├── config.go
├── server.go
├── database.go
├── handlers.go
├── middleware.go
├── logger.go
├── go.mod
└── README.md
1. go.mod
go Copy code
module github.com/example/microservice
go 1.21
require (
github.com/lib/pq v1.10.9
go.uber.org/zap v1.26.0
)
2. logger.go
go Copy code
package main
import (
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
var logger *zap.Logger
// InitLogger initializes the global logger
func InitLogger(env string) error {
var config zap.Config
if env == "production" {
config = zap.NewProductionConfig()
} else {
config = zap.NewDevelopmentConfig()
config.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
}
var err error
logger, err = config.Build()
if err != nil {
return err
}
return nil
}
// GetLogger returns the global logger
func GetLogger() *zap.Logger {
if logger == nil {
// Fallback logger if InitLogger wasn't called
logger, _ = zap.NewProduction()
}
return logger
}
// SyncLogger flushes any buffered log entries
func SyncLogger() error {
if logger != nil {
return logger.Sync()
}
return nil
}
3. config.go
go Copy code
package main
import (
"os"
"strconv"
"time"
)
// Config holds application configuration
type Config struct {
// Server
Port int
Host string
ReadTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout time.Duration
ShutdownTimeout time.Duration
MaxConcurrentRequests int
// Database
DBHost string
DBPort int
DBUser string
DBPassword string
DBName string
DBSSLMode string
MaxDBConn int
MinDBConn int
// Environment
Environment string
}
// LoadConfig loads configuration from environment variables
func LoadConfig() *Config {
return &Config{
Port: getEnvInt("PORT", 8080),
Host: getEnvString("HOST", "0.0.0.0"),
ReadTimeout: getEnvDuration("READ_TIMEOUT", 15*time.Second),
WriteTimeout: getEnvDuration("WRITE_TIMEOUT", 15*time.Second),
IdleTimeout: getEnvDuration("IDLE_TIMEOUT", 60*time.Second),
ShutdownTimeout: getEnvDuration("SHUTDOWN_TIMEOUT", 30*time.Second),
MaxConcurrentRequests: getEnvInt("MAX_CONCURRENT_REQUESTS", 1000),
DBHost: getEnvString("DB_HOST", "localhost"),
DBPort: getEnvInt("DB_PORT", 5432),
DBUser: getEnvString("DB_USER", "postgres"),
DBPassword: getEnvString("DB_PASSWORD", ""),
DBName: getEnvString("DB_NAME", "microservice"),
DBSSLMode: getEnvString("DB_SSL_MODE", "disable"),
MaxDBConn: getEnvInt("MAX_DB_CONN", 25),
MinDBConn: getEnvInt("MIN_DB_CONN", 5),
Environment: getEnvString("ENVIRONMENT", "development"),
}
}
func getEnvString(key, defaultValue string) string {
if value, exists := os.LookupEnv(key); exists {
return value
}
return defaultValue
}
func getEnvInt(key string, defaultValue int) int {
if value, exists := os.LookupEnv(key); exists {
if intValue, err := strconv.Atoi(value); err == nil {
return intValue
}
}
return defaultValue
}
func getEnvDuration(key string, defaultValue time.Duration) time.Duration {
if value, exists := os.LookupEnv(key); exists {
if duration, err := time.ParseDuration(value); err == nil {
return duration
}
}
return defaultValue
}
4. database.go
5. middleware.go
6. handlers.go
7. server.go
8. main.go
go Copy code
package main
import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
"time"
"go.uber.org/zap"
)
// Custom error types
var (
ErrTooManyRequests = fmt.Errorf("too many requests")
)
func main() {
// Load configuration
config := LoadConfig()
// Initialize logger
if err := InitLogger(config.Environment); err != nil {
fmt.Fprintf(os.Stderr, "Failed to initialize logger: %v\n", err)
os.Exit(1)
}
defer SyncLogger()
logger := GetLogger()
logger.Info("Starting microservice",
zap.String("environment", config.Environment),
zap.String("host", config.Host),
zap.Int("port", config.Port),
)
// Initialize database
db, err := NewDatabase(config)
if err != nil {
logger.Fatal("Failed to initialize database",
zap.Error(err),
)
}
// Create and start server
server := NewServer(config, db)
if err := server.Start(); err != nil {
logger.Fatal("Failed to start server",
zap.Error(err),
)
}
// Set up signal handling for graceful shutdown
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGTERM, syscall.SIGINT)
// Wait for shutdown signal
sig := <-sigChan
logger.Info("Received shutdown signal",
zap.String("signal", sig.String()),
)
// Create a context for shutdown operations
shutdownCtx, cancel := context.WithTimeout(context.Background(), config.ShutdownTimeout)
defer cancel()
// Perform graceful shutdown
if err := server.Shutdown(shutdownCtx); err != nil {
logger.Error("Graceful shutdown failed",
zap.Error(err),
)
os.Exit(1)
}
logger.Info("Application exited successfully")
os.Exit(0)
}
9. README.md
markdown Copy code
# Go Microservice Boilerplate
A production-ready microservice template with graceful shutdown, database management, and request tracking.
## Features
- ✅ Graceful shutdown handling (SIGTERM/SIGINT)
- ✅ Active request tracking with configurable limits
- ✅ Request timeout mechanism
- ✅ Database connection pooling
- ✅ Health check endpoints
- ✅ Structured logging (Zap)
- ✅ Middleware support (logging, request tracking)
- ✅ Request ID tracking
- ✅ Database connection cleanup on shutdown
## Environment Variables
```bash
# Server Configuration
PORT=8080
HOST=0.0.0.0
READ_TIMEOUT=15s
WRITE_TIMEOUT=15s
IDLE_TIMEOUT=60s
SHUTDOWN_TIMEOUT=30s
MAX_CONCURRENT_REQUESTS=1000
# Database Configuration
DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=password
DB_NAME=microservice
DB_SSL_MODE=disable
MAX_DB_CONN=25
MIN_DB_CONN=5
# Application
ENVIRONMENT=development # development|production
Running the Service
bash Copy code
# Build
go build -o microservice
# Run
./microservice
# With custom configuration
PORT=9000 SHUTDOWN_TIMEOUT=60s ./microservice
# Docker (example Dockerfile)
docker build -t microservice .
docker run -p 8080:8080 -e ENVIRONMENT=production microservice
API Endpoints
Health Check
bash Copy code
curl http://localhost:8080/health
Response:
json Copy code
{
"status": "healthy",
"timestamp": "2024-01-15T10:30:00Z",
"active_requests": 5,
"database_stats": {
"open_connections": 10,
"in_use": 3,
"idle": 7
},
"shutdown_in_progress": false
}
Readiness Probe
bash Copy code
curl http://localhost:8080/ready
Data Endpoint
bash Copy code
curl -H "X-Request-ID: custom-id" http://localhost:8080/api/data
Graceful Shutdown Flow
Receive SIGTERM/SIGINT signal
Set shutdown flag (stop accepting new requests)
Close HTTP server listener
Wait for active requests to complete (with timeout)
Close database connections
Exit
Dockerfile Example
dockerfile Copy code
FROM golang:1.21-alpine AS builder
WORKDIR /app
COPY . .
RUN go mod download
RUN CGO_ENABLED=0 go build -o microservice .
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /app/microservice .
EXPOSE 8080
ENTRYPOINT ["./microservice"]
Docker Compose Example
yaml Copy code
version: '3.8'
services:
postgres:
image: postgres:15-alpine
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: password
POSTGRES_DB: microservice
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
microservice:
build: .
ports:
- "8080:8080"
environment:
DB_HOST: postgres
DB_USER: postgres
DB_PASSWORD: password
DB_NAME: microservice
ENVIRONMENT: production
depends_on:
- postgres
volumes:
postgres_data:
Testing Graceful Shutdown
bash Copy code
# Start the service
./microservice &
PID=$!
# Make a slow request (10 seconds)
curl --max-time 15 http://localhost:8080/api/data &
# After 5 seconds, send SIGTERM
sleep 5
kill -TERM $PID
# Service will wait for the slow request to finish before exiting
Monitoring
Metrics to Track
Active request count
Database connection pool stats
Request latency
Shutdown duration
Failed requests
Logging
All events are logged with structured logging:
json Copy code
{
"level": "info",
"timestamp": "2024-01-15T10:30:00Z",
"logger": "microservice",
"msg": "HTTP request completed",
"request_id": "20240115103000-abc12345",
"method": "GET",
"path": "/api/data",
"status": 200,
"duration": "150ms"
}
License
MIT
code Copy code
## Key Features Explained
### 1. **Graceful Shutdown**
- Catches SIGTERM/SIGINT signals
- Stops accepting new requests immediately
- Waits for active requests with configurable timeout
- Properly closes database connections
### 2. **Request Tracking**
- Atomic counter for active requests
- WaitGroup for synchronization
- Max concurrent request limit
- Request ID propagation
### 3. **Database Management**
- Connection pooling with configurable limits
- Graceful connection closing
- Health checks with timeouts
- Thread-safe operations
### 4. **Middleware**
- Request tracking and ID propagation
- Structured logging
- Easy to extend
### 5. **Configuration**
- Environment variable based
- Sensible defaults
- Production-ready settings
This boilerplate provides everything needed for a production-ready Go microservice!