foundation

package module
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2025 License: Apache-2.0 Imports: 0 Imported by: 0

README

foundation

A comprehensive toolkit for building secure, scalable web applications in Go. The library implements modern patterns including generics for type safety, functional options for configuration, and interface-based design for flexibility and testability.

Ask DeepWiki GitHub tag (latest SemVer) Go Reference License

Tests CodeQL Analysis GolangCI Lint Go Report Card

Installation

go get github.com/dmitrymomot/foundation

Why Foundation Exists

After building multiple Go web applications, I got tired of doing the same work over and over - copy-pasting request handlers between projects, creating huge boilerplate files to work around framework limitations, reimplementing session management for the third time. Each new project meant another week of setup before writing actual business logic.

Foundation is my solution: all the repetitive code I kept rewriting, collected into reusable packages. It's designed to speed up my own project delivery by providing the pieces I always need - type-safe routing with generics, session management, request validation, background jobs - without the ceremony.

No framework lock-in, no magic. Just composable packages that solve common problems so I can focus on building features instead of reinventing infrastructure.

Quick Start

package main

import (
	"context"
	"database/sql"
	"log"

	"github.com/dmitrymomot/foundation/core/handler"
	"github.com/dmitrymomot/foundation/core/response"
	"github.com/dmitrymomot/foundation/core/router"
	"github.com/dmitrymomot/foundation/core/server"
	"github.com/dmitrymomot/foundation/middleware"
)

// Define your custom context with exactly what you need
type AppContext struct {
	*router.Context
	DB       *sql.DB
	UserID   string
	TenantID string
}

func main() {
	r := router.New[*AppContext]()

	// Add middleware
	r.Use(middleware.CORS[*AppContext]())
	r.Use(middleware.RequestID[*AppContext]())
	r.Use(middleware.Logging[*AppContext]())

	// Type-safe handlers - no casting needed
	r.Get("/", func(ctx *AppContext) handler.Response {
		return response.JSON(map[string]string{
			"status":   "ok",
			"user_id":  ctx.UserID,
			"tenant":   ctx.TenantID,
		})
	})

	r.Get("/users/{id}", func(ctx *AppContext) handler.Response {
		userID := ctx.Param("id")
		// ctx.DB is available with full type safety
		return response.JSON(map[string]string{
			"user_id": userID,
			"message": "User found",
		})
	})

	// Create and run server with graceful shutdown
	ctx := context.Background()
	if err := server.Run(ctx, ":8080", r); err != nil {
		log.Fatal(err)
	}
}

Common Patterns

Multi-tenant SaaS: Session management with tenant isolation, rate limiting per tenant, JWT authentication with tenant claims Background Processing: Queue jobs, schedule tasks, process webhooks with retries, CQRS command/event patterns Security: Input sanitization, TOTP 2FA, AES encryption, secure token generation, device fingerprinting Observability: Structured logging with slog, request ID tracking, health check endpoints

Features

The foundation library is organized into four main categories, providing everything needed to build production-ready web applications:

Core Framework (22 packages)

Request & Response

  • HTTP request data binding with validation (core/binder)
  • Multiple response formats: JSON, HTML, SSE, WebSocket (core/response)
  • Secure cookie management with encryption (core/cookie)
  • Type-safe handler abstractions with generics (core/handler)

Routing & Server

  • High-performance HTTP router with middleware support (core/router)
  • HTTP server with graceful shutdown (core/server)
  • Static file serving with SPA support (core/static)
  • Let's Encrypt certificate management (core/letsencrypt)

State Management

  • Generic session system with pluggable transports (core/session, core/sessiontransport)
  • Thread-safe LRU cache implementation (core/cache)
  • Local filesystem storage with security features (core/storage)

Background Work & Architecture

  • Job queue system with workers and scheduling (core/queue)
  • CQRS command pattern with handlers and message bus (core/command)
  • Event-driven architecture with type-safe handlers (core/event)

Security & Validation

  • Input sanitization and data cleaning (core/sanitizer)
  • Rule-based data validation system (core/validator)

Operations & Configuration

  • Type-safe environment variable loading (core/config)
  • Structured logging built on slog (core/logger)
  • Health monitoring endpoints (core/health)
  • Internationalization with CLDR plural rules (core/i18n)
  • Email sending interface with template support (core/email)
HTTP Middleware

Pre-built middleware components for common cross-cutting concerns:

  • Security: CORS, JWT authentication, security headers
  • Observability: Request logging, request ID tracking
  • Performance: Rate limiting, request timeout handling
  • Development: Debug utilities, request/response debugging
Utilities (16 packages)

Standalone packages providing specific functionality:

  • Security: JWT tokens (pkg/jwt), TOTP authentication (pkg/totp), AES encryption (pkg/secrets), secure token generation (pkg/token)
  • Rate Limiting: Token bucket implementation with pluggable storage (pkg/ratelimiter)
  • Async Programming: Future pattern utilities (pkg/async)
  • Communication: Pub/sub messaging system (pkg/broadcast), webhook delivery with retries (pkg/webhook)
  • AI & ML: Text to vector embeddings using OpenAI and Google AI (pkg/vectorizer)
  • Web Utilities: Client IP extraction (pkg/clientip), User-Agent parsing (pkg/useragent), device fingerprinting (pkg/fingerprint)
  • Content Generation: QR code generation (pkg/qrcode), URL-safe slugs (pkg/slug), random name generation (pkg/randomname)
  • Feature Management: Feature flagging with rollout strategies (pkg/feature)
Integrations (7 packages)

Production-ready integrations for databases, email services, and storage:

  • Databases: PostgreSQL with migrations and connection pooling (integration/database/pg), MongoDB with health checking (integration/database/mongo), Redis with retry logic (integration/database/redis), OpenSearch client (integration/database/opensearch)
  • Email Services: Postmark API integration (integration/email/postmark), SMTP sending (integration/email/smtp)
  • Storage: S3-compatible object storage (integration/storage/s3)

Architecture Patterns

The foundation library follows these key architectural patterns:

  • Generics for type safety: Custom context types eliminate runtime type assertions
  • Functional options: Flexible configuration without breaking changes
  • Interface-based design: Pluggable implementations for testing and modularity
  • Security-first approach: Built-in sanitization, validation, and encryption
  • Multi-tenant considerations: Tenant isolation patterns throughout the design

Documentation

For detailed documentation on any package, use the go doc command:

go doc github.com/dmitrymomot/foundation/core/binder
go doc -all github.com/dmitrymomot/foundation/middleware

Each package contains comprehensive documentation with usage examples and detailed API references.

Requirements

  • Go 1.24 or later

Status

Active development with breaking changes allowed as we work towards v1.0. Production use is at your own discretion - API stability not yet guaranteed.

License

Licensed under the Apache License, Version 2.0. See LICENSE for the full license text.

Contributing

Contributions are welcome! This is an actively developed library, and breaking changes are allowed as we work towards a stable API.

Documentation

Overview

Package foundation provides a comprehensive toolkit for building secure, scalable web applications with a focus on B2B micro-SaaS development. The library implements modern Go patterns including generics for type safety, functional options for configuration, and interface-based design for flexibility and testability.

LLM Assistant Note

This file serves as a comprehensive index of all packages in the foundation library, designed to help LLMs understand the complete codebase structure and functionality. Each package entry includes the full import path and a concise description of its purpose.

Package Organization

The foundation library is organized into four main categories:

  • Core: Framework components for building web applications
  • Middleware: HTTP middleware for cross-cutting concerns
  • Utilities: Standalone packages for common functionality
  • Integrations: Database, email, and storage service implementations

Getting Documentation

For detailed documentation on any package, use the go doc command:

go doc github.com/dmitrymomot/foundation/core/binder
go doc -all github.com/dmitrymomot/foundation/middleware

Core Framework Packages

These packages provide the fundamental building blocks for web applications:

github.com/dmitrymomot/foundation/core/binder        - HTTP request data binding with validation
github.com/dmitrymomot/foundation/core/cache         - Thread-safe LRU cache implementation
github.com/dmitrymomot/foundation/core/command       - CQRS command pattern with handlers and message bus
github.com/dmitrymomot/foundation/core/config        - Type-safe environment variable loading
github.com/dmitrymomot/foundation/core/cookie        - Secure HTTP cookie management with encryption
github.com/dmitrymomot/foundation/core/email         - Email sending interface with template support
github.com/dmitrymomot/foundation/core/email/templates - Email template rendering using templ
github.com/dmitrymomot/foundation/core/email/templates/components - Reusable email template components
github.com/dmitrymomot/foundation/core/event         - Event-driven architecture with type-safe handlers
github.com/dmitrymomot/foundation/core/handler       - Type-safe HTTP handler abstractions
github.com/dmitrymomot/foundation/core/health        - HTTP handlers for service health monitoring
github.com/dmitrymomot/foundation/core/i18n          - Internationalization with CLDR plural rules
github.com/dmitrymomot/foundation/core/letsencrypt   - Let's Encrypt certificate management with explicit control
github.com/dmitrymomot/foundation/core/logger        - Structured logging built on slog
github.com/dmitrymomot/foundation/core/queue         - Job queue system with workers and scheduling
github.com/dmitrymomot/foundation/core/response      - HTTP response utilities (JSON, HTML, SSE, WebSocket)
github.com/dmitrymomot/foundation/core/router        - High-performance HTTP router with middleware
github.com/dmitrymomot/foundation/core/sanitizer     - Input sanitization and data cleaning
github.com/dmitrymomot/foundation/core/server        - HTTP server with graceful shutdown
github.com/dmitrymomot/foundation/core/session       - Generic session management system
github.com/dmitrymomot/foundation/core/sessiontransport - Session transport implementations (cookie, JWT)
github.com/dmitrymomot/foundation/core/static        - Handlers for serving static files, directories, and SPAs
github.com/dmitrymomot/foundation/core/storage       - Local filesystem storage with security features
github.com/dmitrymomot/foundation/core/validator     - Rule-based data validation system

HTTP Middleware Packages

Pre-built middleware components for common cross-cutting concerns:

github.com/dmitrymomot/foundation/middleware         - CORS, JWT auth, rate limiting, security headers, logging

Utility Packages

Standalone packages providing specific functionality:

github.com/dmitrymomot/foundation/pkg/async          - Asynchronous programming utilities with Future pattern
github.com/dmitrymomot/foundation/pkg/broadcast      - Generic pub/sub messaging system
github.com/dmitrymomot/foundation/pkg/clientip       - Real client IP extraction from HTTP requests
github.com/dmitrymomot/foundation/pkg/feature        - Feature flagging system with rollout strategies
github.com/dmitrymomot/foundation/pkg/fingerprint    - Device fingerprint generation for session validation
github.com/dmitrymomot/foundation/pkg/jwt            - RFC 7519 JSON Web Token implementation
github.com/dmitrymomot/foundation/pkg/qrcode         - QR code generation utilities
github.com/dmitrymomot/foundation/pkg/randomname     - Human-readable random name generation
github.com/dmitrymomot/foundation/pkg/ratelimiter    - Token bucket rate limiting with pluggable storage
github.com/dmitrymomot/foundation/pkg/secrets        - AES-256-GCM encryption with compound key derivation
github.com/dmitrymomot/foundation/pkg/slug           - URL-safe slug generation with Unicode normalization
github.com/dmitrymomot/foundation/pkg/token          - Compact URL-safe token generation with HMAC signatures
github.com/dmitrymomot/foundation/pkg/totp           - RFC 6238 TOTP authentication with encrypted secrets
github.com/dmitrymomot/foundation/pkg/useragent      - User-Agent parsing for browser and device detection
github.com/dmitrymomot/foundation/pkg/vectorizer     - Text to vector embeddings using AI providers (OpenAI, Google AI)
github.com/dmitrymomot/foundation/pkg/webhook        - Reliable HTTP webhook delivery with retries

Integration Packages

Production-ready integrations for databases, email services, and storage:

github.com/dmitrymomot/foundation/integration/database/mongo      - MongoDB client with health checking
github.com/dmitrymomot/foundation/integration/database/opensearch - OpenSearch client initialization
github.com/dmitrymomot/foundation/integration/database/pg         - PostgreSQL with migrations and pooling
github.com/dmitrymomot/foundation/integration/database/redis      - Redis client with retry logic
github.com/dmitrymomot/foundation/integration/email/postmark      - Postmark email service integration
github.com/dmitrymomot/foundation/integration/email/smtp          - SMTP email sending implementation
github.com/dmitrymomot/foundation/integration/storage/s3          - S3-compatible storage implementation

Architecture Patterns

The foundation library follows these key architectural patterns:

  • Generics for type safety with custom context types
  • Functional options for flexible configuration
  • Interface-based design for testability and modularity
  • Security-first approach with built-in sanitization and validation
  • Multi-tenant considerations throughout the design

Example Usage

import (
	"context"
	"log"

	"github.com/dmitrymomot/foundation/core/handler"
	"github.com/dmitrymomot/foundation/core/response"
	"github.com/dmitrymomot/foundation/core/router"
	"github.com/dmitrymomot/foundation/core/server"
	"github.com/dmitrymomot/foundation/middleware"
)

func main() {
	// Create router with router.Context
	r := router.New[*router.Context]()

	// Add middleware
	r.Use(middleware.CORS[*router.Context]())
	r.Use(middleware.RequestID[*router.Context]())
	r.Use(middleware.Logging[*router.Context]())

	// Define handlers that return Response functions
	r.Get("/", func(ctx *router.Context) handler.Response {
		return response.JSON(map[string]string{"status": "ok"})
	})

	r.Get("/users/{id}", func(ctx *router.Context) handler.Response {
		userID := ctx.Param("id")
		return response.JSON(map[string]string{
			"user_id": userID,
			"message": "User found",
		})
	})

	// Create and run server
	ctx := context.Background()
	if err := server.Run(ctx, ":8080", r); err != nil {
		log.Fatal(err)
	}
}

For complete examples and detailed usage instructions, refer to the individual package documentation using the go doc command.

Directories

Path Synopsis
_examples
api command
web command
core
binder
Package binder provides comprehensive HTTP request data binding utilities for Go web applications.
Package binder provides comprehensive HTTP request data binding utilities for Go web applications.
cache
Package cache provides a thread-safe LRU cache implementation.
Package cache provides a thread-safe LRU cache implementation.
command
Package command provides a type-safe CQRS command pattern implementation for Go applications.
Package command provides a type-safe CQRS command pattern implementation for Go applications.
config
Package config provides type-safe environment variable loading with caching using Go generics.
Package config provides type-safe environment variable loading with caching using Go generics.
cookie
Package cookie provides secure HTTP cookie management with encryption, signing, and GDPR consent support for web applications.
Package cookie provides secure HTTP cookie management with encryption, signing, and GDPR consent support for web applications.
email
Package email provides a simple, flexible email sending interface with built-in development mode and template rendering support.
Package email provides a simple, flexible email sending interface with built-in development mode and template rendering support.
email/templates
Package templates provides email template rendering using the templ templating engine.
Package templates provides email template rendering using the templ templating engine.
email/templates/components
templ: version: v0.3.906
templ: version: v0.3.906
event
Package event provides a type-safe, extensible event processing system for building event-driven architectures.
Package event provides a type-safe, extensible event processing system for building event-driven architectures.
handler
Package handler provides type-safe HTTP handler abstractions with support for custom context types, middleware composition, and clean error handling.
Package handler provides type-safe HTTP handler abstractions with support for custom context types, middleware composition, and clean error handling.
health
Package health provides HTTP handlers for service health monitoring.
Package health provides HTTP handlers for service health monitoring.
i18n
Package i18n provides internationalization support with immutable, thread-safe design and comprehensive locale handling for Go applications.
Package i18n provides internationalization support with immutable, thread-safe design and comprehensive locale handling for Go applications.
letsencrypt
Package letsencrypt provides Let's Encrypt certificate management with explicit control over certificate operations.
Package letsencrypt provides Let's Encrypt certificate management with explicit control over certificate operations.
logger
Package logger provides structured logging utilities built on Go's standard slog package.
Package logger provides structured logging utilities built on Go's standard slog package.
queue
Package queue provides a job queue system for background task processing with workers, scheduling, and priority-based execution.
Package queue provides a job queue system for background task processing with workers, scheduling, and priority-based execution.
response
Package response provides HTTP response utilities for web applications.
Package response provides HTTP response utilities for web applications.
router
Package router provides a high-performance, type-safe HTTP router with middleware support built on top of a radix tree for efficient path matching.
Package router provides a high-performance, type-safe HTTP router with middleware support built on top of a radix tree for efficient path matching.
sanitizer
Package sanitizer provides comprehensive input sanitization and data cleaning utilities for web applications.
Package sanitizer provides comprehensive input sanitization and data cleaning utilities for web applications.
server
Package server provides production-ready HTTP/HTTPS servers with graceful shutdown, configurable timeouts, and automatic Let's Encrypt certificate management.
Package server provides production-ready HTTP/HTTPS servers with graceful shutdown, configurable timeouts, and automatic Let's Encrypt certificate management.
session
Package session provides pure business logic for managing user sessions with generic data storage.
Package session provides pure business logic for managing user sessions with generic data storage.
sessiontransport
Package sessiontransport provides HTTP transport implementations for session management.
Package sessiontransport provides HTTP transport implementations for session management.
static
Package static provides handlers for serving static files, directories, and Single Page Applications (SPAs).
Package static provides handlers for serving static files, directories, and Single Page Applications (SPAs).
storage
Package storage provides local filesystem storage for handling multipart file uploads with security features including path traversal protection, MIME type validation, and file type checking.
Package storage provides local filesystem storage for handling multipart file uploads with security features including path traversal protection, MIME type validation, and file type checking.
validator
Package validator provides a rule-based data validation system with both programmatic and struct tag-based validation capabilities.
Package validator provides a rule-based data validation system with both programmatic and struct tag-based validation capabilities.
integration
database/mongo
Package mongo provides production-ready MongoDB client initialization and health checking for SaaS applications.
Package mongo provides production-ready MongoDB client initialization and health checking for SaaS applications.
database/opensearch
Package opensearch provides production-ready OpenSearch client initialization with immediate health verification.
Package opensearch provides production-ready OpenSearch client initialization with immediate health verification.
database/pg
Package pg provides production-ready PostgreSQL connection management with migrations and health checking for SaaS applications.
Package pg provides production-ready PostgreSQL connection management with migrations and health checking for SaaS applications.
database/redis
Package redis provides Redis client initialization with connection retry logic and health checking.
Package redis provides Redis client initialization with connection retry logic and health checking.
email/postmark
Package postmark provides Postmark email service integration implementing the core email.EmailSender interface.
Package postmark provides Postmark email service integration implementing the core email.EmailSender interface.
email/smtp
Package smtp provides an SMTP-based implementation of the email.EmailSender interface.
Package smtp provides an SMTP-based implementation of the email.EmailSender interface.
storage/s3
Package s3 provides Amazon S3 and S3-compatible storage implementation.
Package s3 provides Amazon S3 and S3-compatible storage implementation.
Package middleware provides HTTP middleware components for common cross-cutting concerns in web applications.
Package middleware provides HTTP middleware components for common cross-cutting concerns in web applications.
pkg
async
Package async provides utilities for asynchronous programming with Go generics.
Package async provides utilities for asynchronous programming with Go generics.
broadcast
Package broadcast provides a generic pub/sub messaging system with pluggable backends.
Package broadcast provides a generic pub/sub messaging system with pluggable backends.
clientip
Package clientip extracts real client IP addresses from HTTP requests.
Package clientip extracts real client IP addresses from HTTP requests.
feature
Package feature provides a flexible and extensible feature flagging system for Go applications.
Package feature provides a flexible and extensible feature flagging system for Go applications.
fingerprint
Package fingerprint provides device fingerprinting from HTTP requests for session validation and security.
Package fingerprint provides device fingerprinting from HTTP requests for session validation and security.
jwt
Package jwt provides RFC 7519 compliant JSON Web Token implementation using HMAC-SHA256.
Package jwt provides RFC 7519 compliant JSON Web Token implementation using HMAC-SHA256.
qrcode
Package qrcode provides QR code generation utilities for web applications.
Package qrcode provides QR code generation utilities for web applications.
randomname
Package randomname generates human-readable random names using cryptographically secure randomness.
Package randomname generates human-readable random names using cryptographically secure randomness.
ratelimiter
Package ratelimiter provides token bucket rate limiting with pluggable storage backends.
Package ratelimiter provides token bucket rate limiting with pluggable storage backends.
secrets
Package secrets provides AES-256-GCM encryption with compound key derivation for secure data storage.
Package secrets provides AES-256-GCM encryption with compound key derivation for secure data storage.
slug
Package slug generates URL-safe slugs from arbitrary strings with Unicode normalization.
Package slug generates URL-safe slugs from arbitrary strings with Unicode normalization.
token
Package token provides compact, URL-safe token generation and verification using HMAC signatures.
Package token provides compact, URL-safe token generation and verification using HMAC signatures.
totp
Package totp provides RFC 6238 compliant Time-based One-Time Password (TOTP) authentication with AES-256-GCM secret encryption and backup recovery codes.
Package totp provides RFC 6238 compliant Time-based One-Time Password (TOTP) authentication with AES-256-GCM secret encryption and backup recovery codes.
totp/cmd command
useragent
Package useragent provides User-Agent string parsing to extract browser, operating system, and device information for web analytics, content optimization, and request handling.
Package useragent provides User-Agent string parsing to extract browser, operating system, and device information for web analytics, content optimization, and request handling.
vectorizer
Package vectorizer provides unified interfaces and implementations for converting text into vector embeddings using different AI providers.
Package vectorizer provides unified interfaces and implementations for converting text into vector embeddings using different AI providers.
webhook
Package webhook provides reliable HTTP webhook delivery with automatic retries and circuit breaking.
Package webhook provides reliable HTTP webhook delivery with automatic retries and circuit breaking.

Jump to

Keyboard shortcuts

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