foundation

package module
v0.2.10 Latest Latest
Warning

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

Go to latest
Published: Sep 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

Features

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

Core Framework (18 packages)

Essential building blocks for web applications:

  • Request Handling: HTTP request data binding with validation (core/binder)
  • Routing: High-performance HTTP router with middleware support (core/router)
  • Type-Safe Handlers: Generic handler abstractions for better type safety (core/handler)
  • Response Utilities: JSON, HTML, SSE, and WebSocket response helpers (core/response)
  • Server Management: HTTP server with graceful shutdown (core/server)
  • Session Management: Generic session system with pluggable transports (core/session, core/sessiontransport)
  • Configuration: Type-safe environment variable loading (core/config)
  • Security: Input sanitization, secure cookies, data validation (core/sanitizer, core/cookie, core/validator)
  • Storage & Caching: Local filesystem storage and thread-safe LRU cache (core/storage, core/cache)
  • Background Processing: Job queue system with workers and scheduling (core/queue)
  • Utilities: Structured logging, internationalization, email interface (core/logger, core/i18n, 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 (15 packages)

Standalone packages providing specific functionality:

  • Security: JWT tokens (pkg/jwt), TOTP authentication (pkg/totp), AES encryption (pkg/secrets)
  • 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 (pkg/webhook)
  • Utilities: QR code generation (pkg/qrcode), URL-safe slugs (pkg/slug), random names (pkg/randomname)
  • Web Features: Client IP extraction (pkg/clientip), User-Agent parsing (pkg/useragent)
  • Development: Device fingerprinting (pkg/fingerprint), feature flags (pkg/feature), secure tokens (pkg/token)
Integrations (7 packages)

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

  • Databases: PostgreSQL with migrations (integration/database/pg), MongoDB (integration/database/mongo), Redis (integration/database/redis), OpenSearch (integration/database/opensearch)
  • Email Services: Postmark integration (integration/email/postmark), SMTP support (integration/email/smtp)
  • Storage: S3-compatible storage implementation (integration/storage/s3)

Quick Start

package main

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)
	}
}

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
  • Modular architecture allowing composable and flexible 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

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/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/handler       - Type-safe HTTP handler abstractions
github.com/dmitrymomot/foundation/core/i18n          - Internationalization with CLDR plural rules
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/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/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
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.
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
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.
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 comprehensive job queue system with workers, scheduling, and priority-based task processing.
Package queue provides a comprehensive job queue system with workers, scheduling, and priority-based task processing.
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 a robust HTTP server implementation with graceful shutdown, configurable options, and production-ready defaults.
Package server provides a robust HTTP server implementation with graceful shutdown, configurable options, and production-ready defaults.
session
Package session provides secure, generic session management for Go web applications.
Package session provides secure, generic session management for Go web applications.
sessiontransport
Package sessiontransport provides secure transport implementations for the session package.
Package sessiontransport provides secure transport implementations for the session package.
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 generates device fingerprints from HTTP requests for session validation.
Package fingerprint generates device fingerprints from HTTP requests for session validation.
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.
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