README
¶
Go Framework
A lightweight, production-ready Go framework for building cloud-native microservices with built-in observability, health checking, and graceful shutdown.
Features
- HTTP Server: Built on Fiber with sensible defaults
- Structured Logging: Sampled JSON logging using Go's
slog - Metrics: Prometheus-compatible metrics with VictoriaMetrics
- Distributed Tracing: OpenTelemetry integration with configurable sampling
- Health Checks: Kubernetes-style liveness and readiness probes
- Profiling: Built-in pprof endpoints for performance analysis
- Graceful Shutdown: Proper cleanup of resources on termination
- Background Tasks: Managed background workers with context cancellation
- Configuration: Environment variable-based config with validation
Quick Start
Installation
go get github.com/infra-incubator/go-framework
Basic Example
package main
import (
"context"
"github.com/infra-incubator/go-framework/framework"
)
type Config struct {
framework.BaseConfig
// Add your custom config fields here
}
func main() {
// Load configuration from environment variables
cfg := &Config{}
if err := framework.LoadConfig(cfg); err != nil {
panic(err)
}
// Create application with desired features
app, err := framework.New(
cfg,
framework.WithMetrics(),
framework.WithHealth(),
framework.WithTracing(),
)
if err != nil {
panic(err)
}
// Define routes
app.Fiber().Get("/api/hello", func(c *fiber.Ctx) error {
return c.JSON(map[string]string{"message": "Hello, World!"})
})
// Register health check
app.Health().RegisterCheck("service", func(ctx context.Context) error {
return nil // Check your dependencies here
})
// Run application (blocks until shutdown signal)
if err := app.Run(); err != nil {
panic(err)
}
}
Running the Application
# Set required environment variables
export APP_NAME=my-service
export HTTP_PORT=8080
# Run
go run main.go
Configuration
Configure your application using environment variables:
Required Variables
APP_NAME- Application name (required)
Application
APP_VERSION- Application version (default: "dev")APP_COMMIT- Git commit hashENVIRONMENT- Deployment environment (default: "development")
HTTP Server
HTTP_PORT- HTTP server port (default: 8080)HTTP_READ_TIMEOUT- Read timeout in seconds (default: 30)HTTP_WRITE_TIMEOUT- Write timeout in seconds (default: 30)HTTP_IDLE_TIMEOUT- Idle timeout in seconds (default: 120)HTTP_BODY_LIMIT- Max body size (default: "4MB")HTTP_PRINT_ROUTES- Print routes on startup (default: false)HTTP_PREFORK- Enable prefork mode (default: false)
Logging
LOG_LEVEL- Log level: debug, info, warn, error (default: "info")LOG_SAMPLING_RATE- Sampling rate 0.0-1.0 (default: 1.0, no sampling)
Metrics
METRICS_ENABLED- Enable metrics (default: true)METRICS_PORT- Metrics server port (default: 9090)METRICS_PATH- Metrics endpoint path (default: "/metrics")
Health Checks
HEALTH_ENABLED- Enable health checks (default: true)HEALTH_PORT- Health server port (default: 8081)
Tracing
OTEL_ENABLED- Enable OpenTelemetry (default: true)OTEL_COLLECTOR_URL- OTEL collector endpointOTEL_SERVICE_NAME- Service name for tracesOTEL_SAMPLING_RATE- Base sampling rate 0.0-1.0 (default: 0.1)OTEL_ALWAYS_SAMPLE_ERRORS- Always trace errors (default: true)OTEL_ALWAYS_SAMPLE_PATHS- Comma-separated paths to always traceOTEL_NEVER_SAMPLE_PATHS- Paths to skip (default: "/health,/metrics")
Profiling
PROFILING_ENABLED- Enable profiling (default: true)PROFILING_PORT- Profiling server port (default: 6060)
Shutdown
SHUTDOWN_TIMEOUT- Graceful shutdown timeout in seconds (default: 30)
Usage Examples
Database Integration
// Register cleanup
app.RegisterCloser("database", func(ctx context.Context) error {
return db.Close()
})
// Register health check
app.Health().RegisterCheck("database", func(ctx context.Context) error {
return db.PingContext(ctx)
})
Background Tasks
app.AddBackgroundTask("data-sync", func(ctx context.Context) error {
ticker := time.NewTicker(5 * time.Minute)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return nil
case <-ticker.C:
// Do your background work
}
}
})
Custom Middleware
app.Fiber().Use(func(c *fiber.Ctx) error {
// Your middleware logic
return c.Next()
})
Built-in Endpoints
Health
GET /health/live- Liveness probe (always returns OK)GET /health/ready- Readiness probe (runs registered checks)
Metrics
GET /metrics- Prometheus metrics endpoint
Profiling
GET /debug/pprof/- pprof indexGET /debug/pprof/heap- Memory profilingGET /debug/pprof/goroutine- Goroutine analysisGET /debug/pprof/profile- CPU profiling (30s)GET /debug/pprof/metadata- Service metadata
Middleware
The framework includes the following HTTP middleware (applied in order):
- Request ID - Generates unique request ID
- Logging - Logs requests with duration
- Recovery - Catches panics and returns 500
- Metrics - Records HTTP metrics
- Tracing - Creates OpenTelemetry spans
Architecture
┌─────────────────────────────────────────┐
│ Your Application │
├─────────────────────────────────────────┤
│ Routes │ Handlers │ Background Tasks │
├─────────────────────────────────────────┤
│ Framework Layer │
│ HTTP │ Logging │ Metrics │ Tracing │
├─────────────────────────────────────────┤
│ External Dependencies │
│ Fiber │ OpenTelemetry │ Prometheus │
└─────────────────────────────────────────┘
Project Structure
go-framework/
├── framework/ # Core framework code
│ ├── app.go # Application lifecycle
│ ├── config.go # Configuration management
│ ├── logger.go # Logging setup
│ ├── metrics.go # Metrics collection
│ ├── probes.go # Health checks
│ ├── closer.go # Graceful shutdown
│ ├── trace/trace.go # Distributed tracing
│ └── middleware/fiber/ # HTTP middleware
└── example/ # Example application
├── example.go # Main entry point
├── config.go # App configuration
└── database.go # Database setup
Dependencies
- Go 1.25+
- Fiber - HTTP framework
- OpenTelemetry - Distributed tracing
- VictoriaMetrics - Metrics
- validator - Config validation
Contributing
Contributions are welcome! Please open an issue or submit a pull request.
License
Apache License
Click to show internal directories.
Click to hide internal directories.