How arthurdotwork/heimdall works
Project Overview
• Heimdall is a lightweight and extensible API Gateway written in Go. Its primary purpose is to handle HTTP routing, proxying to backend services, and managing middleware (such as logging and CORS).
• It is designed to be easily configured via a YAML file and is deployable either as a standalone binary or within a Docker container.
Analyzing the File Structure
• Top-Level Directories/Files:
• "cmd/heimdall": Contains the main entry point (main.go) for the application.
• "internal": Contains the core logic separated into sub-packages:
▸ config – Handles configuration parsing from YAML files.
▸ middleware – Manages the middleware chain, including registration and test files.
▸ proxy – Implements the HTTP proxy handler that forwards requests.
▸ router – Contains routing logic to match endpoints and apply middleware.
▸ server – Sets up the HTTP server and handles graceful shutdown.
• "middleware" (at root): Houses built-in middleware functions (e.g., logger and CORS).
• Configuration examples and deployment files (Dockerfile, Taskfile.yaml, GitHub workflows).
Key System Components & Interactions
a. Main Application Initialization:
• The main.go in cmd/heimdall bootstraps the application by loading configuration (via the internal/config package) and then initializing the server.
b. Configuration Component:
• Uses YAML-based configuration (e.g., config.example.yaml) to define gateway settings, endpoints, and middleware.
• Responsible for reading network timeouts, port settings, and middleware mappings.
c. Middleware Management:
• Built-in middleware components (e.g., logger, CORS) exist in both “middleware” (global resources) and “internal/middleware”.
• The middleware registry and chaining are handled in internal/middleware/chain.go and registry.go.
• Middleware executes in a defined order: global middlewares are applied first, then endpoint-specific ones.
d. Router and Proxy Handling:
• The router (internal/router/router.go) determines which endpoint configuration matches an incoming request, and selects the appropriate middleware chain.
• The proxy handler (internal/proxy/handler.go) forwards requests to the designated backend service.
e. Server:
• The internal/server/server.go sets up the HTTP server, wires in the middleware chain and router, and ensures graceful shutdown based on termination signals.