go-framework

module
v0.0.0-...-04f0c05 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 3, 2025 License: Apache-2.0

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 hash
  • ENVIRONMENT - 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 endpoint
  • OTEL_SERVICE_NAME - Service name for traces
  • OTEL_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 trace
  • OTEL_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 index
  • GET /debug/pprof/heap - Memory profiling
  • GET /debug/pprof/goroutine - Goroutine analysis
  • GET /debug/pprof/profile - CPU profiling (30s)
  • GET /debug/pprof/metadata - Service metadata

Middleware

The framework includes the following HTTP middleware (applied in order):

  1. Request ID - Generates unique request ID
  2. Logging - Logs requests with duration
  3. Recovery - Catches panics and returns 500
  4. Metrics - Records HTTP metrics
  5. 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

Contributing

Contributions are welcome! Please open an issue or submit a pull request.

License

Apache License

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL