### Load Configuration Example Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/configuration.md Implementation example for loading a configuration file and handling potential errors. ```go cfg, err := config.LoadConfig("helios.yaml") if err != nil { log.Fatal(err) } ``` -------------------------------- ### Start Admin API Server Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/admin-api.md Demonstrates how to instantiate the Admin API mux and start the HTTP server. ```go adminMux := adminapi.NewMux(lb, cfg, metrics) server := &http.Server{ Addr: ":9091", Handler: adminMux, } server.ListenAndServe() ``` -------------------------------- ### Size Limit Plugin Example Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/plugins.md Example configuration for the size limit plugin with specific byte limits. ```go // Configured in YAML plugins: chain: - name: size_limit config: max_request_body: 5242880 # 5MB max_response_body: 10485760 # 10MB ``` -------------------------------- ### Example Circuit Breaker Configuration Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/circuit-breaker.md Usage example demonstrating how to instantiate a circuit breaker with custom settings and a state change callback. ```go cb := circuitbreaker.NewCircuitBreaker(circuitbreaker.Settings{ Name: "api-client", MaxRequests: 5, Interval: 60 * time.Second, Timeout: 60 * time.Second, FailureThreshold: 5, SuccessThreshold: 2, OnStateChange: func(name string, from, to circuitbreaker.State) { log.Printf("CB %s: %s → %s", name, from, to) }, }) ``` -------------------------------- ### Install golangci-lint Source: https://github.com/0xrelogic/helios/blob/main/CONTRIBUTING.md Commands to install the golangci-lint tool on different operating systems. ```bash brew install golangci-lint ``` ```bash curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ``` ```bash go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest ``` -------------------------------- ### Server Configuration YAML Example Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/configuration.md Example YAML configuration for the server component. ```yaml server: port: 8080 tls: enabled: true certFile: "certs/cert.pem" keyFile: "certs/key.pem" timeouts: read: 15 write: 15 idle: 60 handler: 30 shutdown: 30 backend_dial: 10 backend_read: 30 backend_idle: 90 ``` -------------------------------- ### Initialize IPHashConsistentStrategy Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/load-balancing-strategies.md Example of how to instantiate the strategy. ```go strategy := loadbalancer.NewIPHashConsistentStrategy() ``` -------------------------------- ### Install dependencies Source: https://github.com/0xrelogic/helios/blob/main/CONTRIBUTING.md Use this command to download the project dependencies. ```bash go mod download ``` -------------------------------- ### Configure Metrics via YAML Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/configuration.md YAML configuration example for setting up the metrics server. ```yaml metrics: enabled: true port: 9090 path: "/metrics" ``` -------------------------------- ### Initialize LeastConnectionsStrategy Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/load-balancing-strategies.md Constructor and usage example for the least connections strategy. ```go func NewLeastConnectionsStrategy() *LeastConnectionsStrategy ``` ```go strategy := loadbalancer.NewLeastConnectionsStrategy() ``` -------------------------------- ### Round Robin Usage Example Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/load-balancing-strategies.md Demonstrates the sequential rotation of backends. ```go // With backends: [server1, server2, server3] rr.NextBackend() // server1 rr.NextBackend() // server2 rr.NextBackend() // server3 rr.NextBackend() // server1 ``` -------------------------------- ### NextBackend Usage Example Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/load-balancing-strategies.md Demonstrates consistent backend selection for a client across backend set changes. ```go // Client 192.0.2.1 with backends [s1, s2, s3] ihc.NextBackend() // server1 // Same client, same backend ihc.NextBackend() // server1 // Add server4: [s1, s2, s3, s4] // 192.0.2.1 still maps to server1 (87% stay same) ihc.NextBackend() // server1 ``` -------------------------------- ### Bucket Cleanup Example Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/rate-limiter.md Demonstrates the behavior of automatic bucket removal for idle client IPs. ```go // After 1 hour of no requests from 192.0.2.5 // The bucket is automatically removed // New request from 192.0.2.5 creates a fresh bucket rl.Allow("192.0.2.5") // New bucket with maxTokens ``` -------------------------------- ### Initialize Load Balancer Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/load-balancer.md Example showing how to load configuration and instantiate the load balancer. Ensure Stop() is deferred to clean up resources. ```go cfg, err := config.LoadConfig("helios.yaml") if err != nil { log.Fatal(err) } lb, err := loadbalancer.NewLoadBalancer(cfg) if err != nil { log.Fatal(err) } defer lb.Stop() ``` -------------------------------- ### Initialize TokenBucketRateLimiter Instances Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/rate-limiter.md Examples of configuring the rate limiter for different request throughput requirements. ```go // Allow 100 requests per second (1 token per 10ms) rl := ratelimiter.NewTokenBucketRateLimiter(100, 10*time.Millisecond) // Allow 10 requests per second (1 token per 100ms) rl := ratelimiter.NewTokenBucketRateLimiter(10, 100*time.Millisecond) // Allow 1 request per second rl := ratelimiter.NewTokenBucketRateLimiter(1, 1*time.Second) ``` -------------------------------- ### Implement Plugin Factory Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/plugins.md Example of registering a custom plugin using the init function. ```go func init() { RegisterBuiltin("custom", func(name string, cfg map[string]interface{}) (Middleware, error) { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Before next handler next.ServeHTTP(w, r) // After next handler }) }, nil }) } ``` -------------------------------- ### Execute Middleware Chain Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/plugins.md Example of building a middleware chain and applying it to a base handler. ```go pluginCfg := config.PluginsConfig{ Enabled: true, Chain: []config.PluginConfig{ {Name: "logging"}, {Name: "size_limit", Config: map[string]interface{}{ "max_request_body": 10485760, }}, }, } handler, err := plugins.BuildChain(pluginCfg, baseHandler) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Initialize WeightedRoundRobinStrategy Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/load-balancing-strategies.md Constructor and usage example for the weighted round robin strategy. ```go func NewWeightedRoundRobinStrategy() *WeightedRoundRobinStrategy ``` ```go strategy := loadbalancer.NewWeightedRoundRobinStrategy() ``` -------------------------------- ### GET /v1/backends Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/admin-api.md Retrieves a list of all configured backends. ```APIDOC ## GET /v1/backends ### Description Returns a list of all currently registered backends. ### Method GET ### Endpoint /v1/backends ``` -------------------------------- ### Log Message Example Source: https://github.com/0xrelogic/helios/blob/main/docs/admin-api-security.md Example of the warning message logged when an IP is blocked. ```text WRN IP blocked by filter client_ip=10.0.0.1 path=/v1/backends ``` -------------------------------- ### IP Hash Selection Examples Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/load-balancing-strategies.md Demonstration of how different client IPs map to backends and maintain session affinity. ```go // Client 192.0.2.1 with backends [s1, s2, s3] // hash(192.0.2.1) % 3 = 1 ih.NextBackend() // server2 // Next request from 192.0.2.1 ih.NextBackend() // server2 (same) // Client 198.51.100.5 // hash(198.51.100.5) % 3 = 0 ih.NextBackend() // server1 ``` -------------------------------- ### GET /v1/backends Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/endpoints.md Lists all configured backends. Requires authentication. ```APIDOC ## GET /v1/backends ### Description Lists all configured backends. Requires authentication. ### Method GET ### Endpoint /v1/backends ``` -------------------------------- ### Initialize and Run Helios Load Balancer in Go Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/load-balancer.md Demonstrates loading configuration, adding backends at runtime, switching strategies, and starting the HTTP server. ```go package main import ( "log" "net/http" "github.com/0xReLogic/Helios/internal/config" "github.com/0xReLogic/Helios/internal/loadbalancer" ) func main() { // Load configuration cfg, err := config.LoadConfig("helios.yaml") if err != nil { log.Fatal(err) } // Create load balancer lb, err := loadbalancer.NewLoadBalancer(cfg) if err != nil { log.Fatal(err) } defer lb.Stop() // Add a backend at runtime lb.AddBackend(config.BackendConfig{ Name: "dynamic-server", Address: "http://localhost:8084", Weight: 1, }) // Switch strategy err = lb.SetStrategy("least_connections") if err != nil { log.Fatal(err) } // List backends backends := lb.ListBackends() for _, b := range backends { log.Printf("Backend: %s, Healthy: %v, Connections: %d", b.Name, b.Healthy, b.ActiveConnections) } // Start server server := &http.Server{ Addr: ":" + "8080", Handler: lb, } if err := server.ListenAndServe(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Configure Plugin Chain in helios.yaml Source: https://github.com/0xrelogic/helios/blob/main/docs/plugin-development.md Example configuration for enabling and ordering plugins in the gateway. ```yaml plugins: enabled: true chain: - name: headers config: set: X-Powered-By: "Helios Gateway" - name: logging ``` -------------------------------- ### Define Backend Configuration Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/configuration.md Defines the structure for backend services and provides a YAML example for implementation. ```go type BackendConfig struct { Name string Address string Weight int } ``` ```yaml backends: - name: "server1" address: "http://localhost:8081" weight: 5 - name: "server2" address: "http://localhost:8082" weight: 2 ``` -------------------------------- ### Run Helios Executable Source: https://github.com/0xrelogic/helios/blob/main/README.md Execute the compiled binary to start the proxy server. ```bash ./helios.exe ``` -------------------------------- ### Log Output Example Source: https://github.com/0xrelogic/helios/blob/main/README.md Sample log entry showing request metadata and trace identifiers. ```text time=2025-10-02T10:30:00Z level=info request_id=req_abc123 trace_id=trace_demo method=GET path=/api/users status=200 latency_ms=45 backend=server1 message="request completed" ``` -------------------------------- ### Verify Request and Trace Propagation Source: https://github.com/0xrelogic/helios/blob/main/README.md Commands to run backends, start the load balancer, and test request tracing. ```bash go run ./cmd/backend --port=8081 --id=server1 ``` ```bash go run ./cmd/helios ``` ```bash curl -H "X-Trace-ID: trace_demo" http://localhost:8080/api/users ``` -------------------------------- ### Initialize Rate Limiter Programmatically Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/rate-limiter.md Examples of creating new token bucket rate limiters with different request throughput settings. ```go // 100 requests per second per client rl := ratelimiter.NewTokenBucketRateLimiter(100, 10*time.Millisecond) // 10 requests per 5 seconds per client rl := ratelimiter.NewTokenBucketRateLimiter(10, 500*time.Millisecond) // 1000 requests per second per client rl := ratelimiter.NewTokenBucketRateLimiter(1000, 1*time.Millisecond) ``` -------------------------------- ### NextBackend Method for Weighted Round Robin Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/load-balancing-strategies.md Method signature, algorithmic logic, and usage example for weighted backend selection. ```go func (wrr *WeightedRoundRobinStrategy) NextBackend(r *http.Request) *Backend ``` ```text index = (current + 1) % len(backends) weighted_index = index % totalWeight // Map to actual backend based on weight distribution ``` ```go // Backends: server1 (weight=5), server2 (weight=2), server3 (weight=1) // Total: 8 slots per cycle wrr.NextBackend() // server1 wrr.NextBackend() // server1 wrr.NextBackend() // server1 wrr.NextBackend() // server1 wrr.NextBackend() // server1 wrr.NextBackend() // server2 wrr.NextBackend() // server2 wrr.NextBackend() // server3 // (cycle repeats) ``` -------------------------------- ### Configure Logging via YAML Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/configuration.md Example YAML configuration for setting log levels, output formats, and request/trace ID headers. ```yaml logging: level: "info" format: "json" include_caller: false request_id: enabled: true header: "X-Request-ID" trace: enabled: true header: "X-Trace-ID" ``` -------------------------------- ### Manage Docker Services Source: https://github.com/0xrelogic/helios/blob/main/README.md Commands to build, start, and stop the Helios containerized environment. ```bash docker-compose up --build ``` ```bash docker-compose up -d --build ``` ```bash docker-compose down ``` -------------------------------- ### Configure Admin API via YAML Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/configuration.md YAML configuration example for the Admin API, including authentication and IP filtering. ```yaml admin_api: enabled: true port: 9091 auth_token: "change-me" ip_allow_list: - "127.0.0.1" - "192.168.1.0/24" ip_deny_list: - "203.0.113.0/24" ``` -------------------------------- ### GET /metrics Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/endpoints.md Retrieves system metrics in Prometheus format. ```APIDOC ## GET /metrics ### Description Returns Prometheus-format metrics from the metrics collector. ### Method GET ### Endpoint /metrics ### Response #### Success Response (200) - **Content-Type** (text/plain; version=0.0.4) - Prometheus-formatted metrics data. ### Request Example curl http://localhost:9090/metrics ``` -------------------------------- ### Configure Load Balancer via YAML Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/configuration.md Example YAML configuration for the load balancer and its associated WebSocket pool. ```yaml load_balancer: strategy: "least_connections" websocket_pool: enabled: true max_idle: 10 max_active: 100 idle_timeout_seconds: 300 ``` -------------------------------- ### Register Metrics Endpoint Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/metrics.md Example of registering the metrics handler to an HTTP ServeMux. ```go mux := http.NewServeMux() mux.Handle("/metrics", mc.MetricsHandler()) ``` -------------------------------- ### Configure Rate Limiter via YAML Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/rate-limiter.md Example configuration for enabling and setting bucket parameters in a YAML file. ```yaml rate_limit: enabled: true max_tokens: 100 refill_rate_seconds: 1 ``` -------------------------------- ### Obtain Production Certificates via Let's Encrypt Source: https://github.com/0xrelogic/helios/blob/main/certs/README.md Installs Certbot and generates a certificate for a specific domain, followed by copying the files to the project directory. ```bash # Install certbot sudo apt-get install certbot # Generate certificate for your domain sudo certbot certonly --standalone -d yourdomain.com # Copy certificates sudo cp /etc/letsencrypt/live/yourdomain.com/fullchain.pem cert.pem sudo cp /etc/letsencrypt/live/yourdomain.com/privkey.pem key.pem ``` -------------------------------- ### Configure Circuit Breaker via YAML Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/configuration.md YAML configuration example for enabling and tuning circuit breaker parameters. ```yaml circuit_breaker: enabled: true max_requests: 5 interval_seconds: 60 timeout_seconds: 60 failure_threshold: 5 success_threshold: 2 ``` -------------------------------- ### Configure Secure Admin API Settings Source: https://github.com/0xrelogic/helios/blob/main/docs/admin-api-security.md A complete configuration example including port settings, authentication tokens, and CIDR-based IP filtering. ```yaml admin_api: enabled: true port: 9091 auth_token: "use-a-strong-random-token-here-min-32-chars" # Allow only internal network ip_allow_list: - "127.0.0.1" # Localhost - "192.168.1.0/24" # Internal network - "10.0.0.0/8" # VPN network # Block known bad actors ip_deny_list: - "203.0.113.0/24" # Known attack subnet - "198.51.100.50" # Specific malicious IP ``` -------------------------------- ### Proxy Response Example Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/endpoints.md Sample HTTP response returned by the proxy, including standard headers and the backend payload. ```http HTTP/1.1 200 OK Content-Type: application/json Content-Length: 42 X-Request-ID: req_abc123 X-Trace-ID: trace123 {"id": 1, "name": "John", "created": true} ``` -------------------------------- ### GET /v1/backends Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/endpoints.md Lists all backends with their current status and configuration. Requires Bearer token authentication. ```APIDOC ## GET /v1/backends ### Description Lists all backends with current status. ### Method GET ### Endpoint /v1/backends ### Response #### Success Response (200) - **name** (string) - Backend identifier - **address** (string) - Backend URL - **healthy** (boolean) - Current health status - **active_connections** (int32) - Active connection count - **weight** (int) - Load balancing weight ``` -------------------------------- ### Initialize Load Balancer Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/README.md Demonstrates loading configuration, initializing the load balancer, adding backends, and setting strategies. ```go package main import ( "log" "github.com/0xReLogic/Helios/internal/config" "github.com/0xReLogic/Helios/internal/loadbalancer" ) func main() { // Load configuration cfg, err := config.LoadConfig("helios.yaml") if err != nil { log.Fatal(err) } // Create load balancer lb, err := loadbalancer.NewLoadBalancer(cfg) if err != nil { log.Fatal(err) } defer lb.Stop() // Add backend at runtime lb.AddBackend(config.BackendConfig{ Name: "server4", Address: "http://localhost:8084", Weight: 1, }) // List backends for _, b := range lb.ListBackends() { log.Printf("Backend: %s (%s)", b.Name, b.Address) } // Switch strategy lb.SetStrategy("least_connections") // Use as HTTP handler // server := &http.Server{Addr: ":8080", Handler: lb} // server.ListenAndServe() } ``` -------------------------------- ### Initialize and Test Load Balancing Strategies in Go Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/load-balancing-strategies.md Demonstrates the instantiation of multiple load balancing strategies and the iterative selection of backends for each. ```go package main import ( "fmt" "github.com/0xReLogic/Helios/internal/config" "github.com/0xReLogic/Helios/internal/loadbalancer" ) func main() { // Create different strategies strategies := map[string]loadbalancer.Strategy{ "round_robin": loadbalancer.NewRoundRobinStrategy(), "least_connections": loadbalancer.NewLeastConnectionsStrategy(), "weighted_round_robin": loadbalancer.NewWeightedRoundRobinStrategy(), "ip_hash": loadbalancer.NewIPHashStrategy(), "ip_hash_consistent": loadbalancer.NewIPHashConsistentStrategy(), } // Add backends to all for _, s := range strategies { s.AddBackend(&loadbalancer.Backend{Name: "server1", Weight: 5}) s.AddBackend(&loadbalancer.Backend{Name: "server2", Weight: 2}) s.AddBackend(&loadbalancer.Backend{Name: "server3", Weight: 1}) } // Test each strategy for name, strategy := range strategies { fmt.Printf("\n=== %s ===\n", name) for i := 0; i < 10; i++ { backend := strategy.NextBackend(nil) fmt.Printf("Request %d -> %s\n", i+1, backend.Name) } } } ``` -------------------------------- ### NewLoadBalancer Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/load-balancer.md Creates a new load balancer instance with the provided configuration, initializes backends, and starts health checks. ```APIDOC ## func NewLoadBalancer(cfg *config.Config) (*LoadBalancer, error) ### Description Creates a new load balancer with the configuration, initializes all backends, and starts health checks. ### Parameters - **cfg** (*config.Config) - Required - Configuration structure ### Returns - **LoadBalancer** (*LoadBalancer) - Initialized load balancer - **error** (error) - Configuration or initialization error ### Example ```go cfg, err := config.LoadConfig("helios.yaml") if err != nil { log.Fatal(err) } lb, err := loadbalancer.NewLoadBalancer(cfg) if err != nil { log.Fatal(err) } defer lb.Stop() ``` ``` -------------------------------- ### Configure Active Health Checks in YAML Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/configuration.md Example YAML configuration for enabling and setting parameters for active health checks. ```yaml health_checks: active: enabled: true interval: 10 timeout: 7 path: "/health" ``` -------------------------------- ### GET /v1/health Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/endpoints.md Performs an administrative health check. ```APIDOC ## GET /v1/health ### Description Performs an administrative health check. ### Method GET ### Endpoint /v1/health ``` -------------------------------- ### GET /health Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/endpoints.md Performs a health check on the service. ```APIDOC ## GET /health ### Description Performs a health check on the service. ### Method GET ### Endpoint /health ``` -------------------------------- ### GET /metrics Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/endpoints.md Retrieves Prometheus metrics from the service. ```APIDOC ## GET /metrics ### Description Retrieves Prometheus metrics for the service. ### Method GET ### Endpoint /metrics ``` -------------------------------- ### Initialize and apply RateLimitMiddleware Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/rate-limiter.md Shows how to instantiate a rate limiter and apply it as middleware to an existing handler. ```go rl := ratelimiter.NewTokenBucketRateLimiter(100, 10*time.Millisecond) middleware := ratelimiter.RateLimitMiddleware(rl) handler := middleware(myHandler) ``` -------------------------------- ### Initialize and Expose Metrics in Go Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/metrics.md Demonstrates how to instantiate a metrics collector, record request data, and expose the metrics via an HTTP handler. ```go package main import ( "net/http" "time" "github.com/0xReLogic/Helios/internal/metrics" ) func main() { mc := metrics.NewMetricsCollector() // Record some requests for i := 0; i < 100; i++ { mc.RecordRequest() success := i%10 != 0 // 90% success rate mc.RecordResponse(success, time.Duration(50+i)*time.Millisecond) mc.RecordBackendRequest("server1", success, time.Duration(45+i)*time.Millisecond) } // Update backend health mc.UpdateBackendHealth("server1", true) mc.UpdateBackendConnections("server1", 10) // Expose metrics http.Handle("/metrics", mc.MetricsHandler()) http.ListenAndServe(":9090", nil) } ``` -------------------------------- ### GET /v1/metrics Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/endpoints.md Retrieves administrative metrics. Requires authentication. ```APIDOC ## GET /v1/metrics ### Description Retrieves administrative metrics. Requires authentication. ### Method GET ### Endpoint /v1/metrics ``` -------------------------------- ### GET /v1/health Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/admin-api.md Performs a health check on the Helios service. ```APIDOC ## GET /v1/health ### Description Checks the health status of the Helios service. ### Method GET ### Endpoint /v1/health ``` -------------------------------- ### GET /health Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/endpoints.md Provides a simple health check status for the service. ```APIDOC ## GET /health ### Description Simple health check endpoint for monitoring. ### Method GET ### Endpoint /health ### Response #### Success Response (200) - **status** (string) - The current health status of the service. #### Response Example { "status": "ok" } ### Request Example curl http://localhost:9090/health ``` -------------------------------- ### Implement Rate Limiter in Go Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/rate-limiter.md Demonstrates initializing the rate limiter and wrapping an HTTP handler with middleware. ```go package main import ( "fmt" "log" "net/http" "github.com/0xReLogic/Helios/internal/ratelimiter" ) func main() { // Create rate limiter: 10 requests per second per client rl := ratelimiter.NewTokenBucketRateLimiter(10, 100*time.Millisecond) // Wrap handler with middleware middleware := ratelimiter.RateLimitMiddleware(rl) handler := middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") fmt.Fprintf(w, `{"message": "Request allowed"}`) })) // Start server log.Printf("Starting server on :8080") log.Fatal(http.ListenAndServe(":8080", handler)) } ``` -------------------------------- ### Get Active Connections Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/load-balancer.md Retrieves the current number of active connections for a backend. ```go connCount := backend.GetActiveConnections() ``` -------------------------------- ### GET /v1/health Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/endpoints.md Performs a health check on the service. This endpoint does not require authentication. ```APIDOC ## GET /v1/health ### Description Performs a health check on the service. ### Method GET ### Endpoint /v1/health ### Response #### Success Response (200) - **status** (string) - Service status ``` -------------------------------- ### Run pre-push checks Source: https://github.com/0xrelogic/helios/blob/main/CONTRIBUTING.md Execute these commands to format, lint, test, and build the project before pushing. ```bash # Format code go fmt ./... # Run linter golangci-lint run # Run tests go test ./... # Build to ensure no compilation errors go build ./... ``` -------------------------------- ### Clone the repository Source: https://github.com/0xrelogic/helios/blob/main/CONTRIBUTING.md Use these commands to clone the repository and enter the project directory. ```bash git clone https://github.com/0xReLogic/Helios.git cd Helios ``` -------------------------------- ### GET /v1/metrics Source: https://github.com/0xrelogic/helios/blob/main/README.md Retrieves detailed metrics for the load balancer. Requires JWT authentication. ```APIDOC ## GET /v1/metrics ### Description Retrieve detailed metrics for the system. ### Method GET ### Endpoint /v1/metrics ``` -------------------------------- ### GET /v1/health Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/admin-api.md Performs a health check on the service. This endpoint is public and does not require authentication. ```APIDOC ## GET /v1/health ### Description Health check endpoint requiring no authentication. ### Method GET ### Endpoint /v1/health ### Response #### Success Response (200) - **status** (string) - Status message ``` -------------------------------- ### Complete Admin API Client Implementation in Go Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/admin-api.md A full client implementation including authentication, request handling, and methods for managing backends and strategies. ```go package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" ) type AdminClient struct { baseURL string token string } func NewAdminClient(baseURL, token string) *AdminClient { return &AdminClient{ baseURL: baseURL, token: token, } } func (ac *AdminClient) do(method, path string, body interface{}) ([]byte, error) { var reqBody io.Reader if body != nil { data, _ := json.Marshal(body) reqBody = bytes.NewReader(data) } req, _ := http.NewRequest(method, ac.baseURL+path, reqBody) req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", ac.token)) req.Header.Set("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req) if err != nil { return nil, err } defer resp.Body.Close() data, _ := io.ReadAll(resp.Body) if resp.StatusCode >= 400 { return nil, fmt.Errorf("status %d: %s", resp.StatusCode, string(data)) } return data, nil } func (ac *AdminClient) Health() error { req, _ := http.NewRequest("GET", ac.baseURL+"/v1/health", nil) resp, _ := http.DefaultClient.Do(req) return resp.Body.Close() } func (ac *AdminClient) ListBackends() ([]map[string]interface{}, error) { data, err := ac.do("GET", "/v1/backends", nil) if err != nil { return nil, err } var backends []map[string]interface{} json.Unmarshal(data, &backends) return backends, nil } func (ac *AdminClient) AddBackend(name, address string, weight int) error { _, err := ac.do("POST", "/v1/backends/add", map[string]interface{}{ "name": name, "address": address, "weight": weight, }) return err } func (ac *AdminClient) RemoveBackend(name string) error { _, err := ac.do("POST", "/v1/backends/remove", map[string]interface{}{ "name": name, }) return err } func (ac *AdminClient) SetStrategy(strategy string) error { _, err := ac.do("POST", "/v1/strategy", map[string]interface{}{ "strategy": strategy, }) return err } func main() { client := NewAdminClient("http://localhost:9091", "change-me") // Health check client.Health() fmt.Println("Health check passed") // List backends backends, _ := client.ListBackends() for _, b := range backends { fmt.Printf("Backend: %v\n", b) } // Add backend client.AddBackend("server4", "http://localhost:8084", 1) fmt.Println("Added backend") // Change strategy client.SetStrategy("least_connections") fmt.Println("Strategy changed") // Remove backend client.RemoveBackend("server4") fmt.Println("Removed backend") } ``` -------------------------------- ### Get Metrics Endpoint Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/endpoints.md Retrieves administrative metrics. Requires a valid Bearer token. ```bash curl -H "Authorization: Bearer my-token" \ http://localhost:9091/v1/metrics ``` -------------------------------- ### Logging Plugin Initialization Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/plugins.md The logging plugin is automatically initialized via init() and requires no additional configuration. ```go // Automatically initialized via init() in logging.go // No additional configuration needed ``` -------------------------------- ### Implement Plugin Factory with Validation Source: https://github.com/0xrelogic/helios/blob/main/docs/plugin-development.md Factory function implementation demonstrating configuration parsing and error handling. ```go func MyPluginFactory(name string, cfg map[string]interface{}) (Middleware, error) { apiKey, ok := cfg["apiKey"].(string) if !ok || apiKey == "" { return nil, fmt.Errorf("apiKey is required for plugin %s", name) } // ... return middleware, nil } ``` -------------------------------- ### Restrictive IP Configuration Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/admin-api.md Example of a restrictive configuration using specific IP addresses and subnets. ```yaml admin_api: enabled: true port: 9091 auth_token: "my-secure-token" ip_allow_list: - "127.0.0.1" # localhost - "192.168.1.100/32" # single admin machine - "10.0.0.0/24" # admin subnet ``` -------------------------------- ### GET /v1/health Source: https://github.com/0xrelogic/helios/blob/main/README.md Retrieves the health status of the load balancer. This endpoint is public and does not require authentication. ```APIDOC ## GET /v1/health ### Description Health check endpoint to verify the status of the load balancer. ### Method GET ### Endpoint /v1/health ``` -------------------------------- ### Run Test Backends Source: https://github.com/0xrelogic/helios/blob/main/README.md Build and run multiple backend servers for testing purposes. ```bash # Build the backend server go build -o backend.exe ./cmd/backend # Run multiple backend servers ./backend.exe --port=8081 --id=1 ./backend.exe --port=8082 --id=2 ./backend.exe --port=8083 --id=3 ``` -------------------------------- ### GET /v1/metrics Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/endpoints.md Retrieves detailed metrics for administrative monitoring. Requires Bearer token authentication. ```APIDOC ## GET /v1/metrics ### Description Returns detailed metrics for administrative monitoring. ### Method GET ### Endpoint /v1/metrics ``` -------------------------------- ### Handle Backend Configuration Errors in Go Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/errors.md Demonstrates error handling when adding a backend with an invalid URL format. ```go err := lb.AddBackend(config.BackendConfig{ Name: "bad-backend", Address: "not-a-url", Weight: 1, }) if err != nil { // "parse not-a-url: invalid URL format" log.Printf("Failed to add backend: %v", err) } ``` -------------------------------- ### GET /v1/metrics Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/admin-api.md Retrieves system metrics in Prometheus format. Requires Bearer token authentication. ```APIDOC ## GET /v1/metrics ### Description Returns detailed metrics in Prometheus format. ### Method GET ### Endpoint /v1/metrics ### Response #### Success Response (200) - **metrics** (string) - Prometheus-format metrics with all counters and gauges. ``` -------------------------------- ### Prometheus Metrics Output Format Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/metrics.md Example of the metrics output generated by the Helios collector in Prometheus format. ```text # HELP helios_requests_total Total HTTP requests received # TYPE helios_requests_total counter helios_requests_total 100 # HELP helios_requests_successful Successful HTTP requests # TYPE helios_requests_successful counter helios_requests_successful 90 # HELP helios_requests_failed Failed HTTP requests # TYPE helios_requests_failed counter helios_requests_failed 10 # HELP helios_response_time_ms Average response time in milliseconds # TYPE helios_response_time_ms gauge helios_response_time_ms 74.5 # HELP helios_backend_requests_total Backend request count # TYPE helios_backend_requests_total counter helios_backend_requests_total{backend="server1"} 100 helios_backend_response_time_ms{backend="server1"} 74.3 helios_backend_healthy{backend="server1"} 1 helios_backend_active_connections{backend="server1"} 10 ``` -------------------------------- ### Parse Plugin Configuration Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/plugins.md Demonstrates how to safely extract and type-cast configuration values from the plugin map. ```go func init() { plugins.RegisterBuiltin("rate_limit", func(name string, cfg map[string]interface{}) (plugins.Middleware, error) { // Parse max_requests maxReqs := 100 if val, ok := cfg["max_requests"]; ok { if v, ok := val.(float64); ok { maxReqs = int(v) } } return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Use maxReqs next.ServeHTTP(w, r) }) }, nil }) } ``` -------------------------------- ### GET /v1/backends Source: https://github.com/0xrelogic/helios/blob/main/README.md Lists all configured backends along with their current health status. Requires JWT authentication. ```APIDOC ## GET /v1/backends ### Description List all backends with health status. ### Method GET ### Endpoint /v1/backends ``` -------------------------------- ### Build and Run Helios Source: https://github.com/0xrelogic/helios/blob/main/README.md Standard commands to clone the repository, compile the binary, and execute the application. ```bash git clone https://github.com/0xReLogic/Helios.git cd Helios go build -o helios ./cmd/helios ./helios ``` -------------------------------- ### Check IP and Update Allow List Source: https://github.com/0xrelogic/helios/blob/main/docs/admin-api-security.md Use this to verify your current public IP address and add it to the configuration file's allow list. ```bash # Check your current IP curl ifconfig.me # Add it to the allow list admin_api: ip_allow_list: - "YOUR_IP_HERE" ``` -------------------------------- ### Execute Backend Batch Script Source: https://github.com/0xrelogic/helios/blob/main/README.md Use the provided Windows batch script to launch test backends. ```bash start_backends.bat ``` -------------------------------- ### List Available Plugins Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/plugins.md Retrieves a list of all registered plugin names. ```go availablePlugins := plugins.List() // Output: ["logging", "size_limit", "gzip", "headers", ...] ``` -------------------------------- ### Run tests Source: https://github.com/0xrelogic/helios/blob/main/CONTRIBUTING.md Use this command to execute all tests in the project. ```bash go test ./... ``` -------------------------------- ### Handle Plugin Initialization Errors Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/plugins.md Check for errors returned by BuildChain to identify initialization failures. ```go handler, err := plugins.BuildChain(cfg.Plugins, baseHandler) if err != nil { // "unknown plugin: invalid_name" // "plugin gzip init failed: invalid compression level" } ``` -------------------------------- ### GET /v1/backends Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/admin-api.md Lists all backends with their current health status and connection count. Requires Bearer token authentication. ```APIDOC ## GET /v1/backends ### Description Lists all backends with their current health status and connection count. ### Method GET ### Endpoint /v1/backends ### Response #### Success Response (200) - **name** (string) - Backend identifier - **address** (string) - Backend URL - **healthy** (boolean) - Current health status - **active_connections** (int32) - Active connection count - **weight** (int) - Load balancing weight ``` -------------------------------- ### Troubleshoot and Clean Up Source: https://github.com/0xrelogic/helios/blob/main/README.md Commands for identifying port conflicts, rebuilding images, and removing volumes. ```bash # Check if ports are already in use lsof -i :8080 lsof -i :9090 lsof -i :9091 ``` ```bash docker-compose down docker-compose build --no-cache docker-compose up ``` ```bash docker-compose down -v --remove-orphans ``` -------------------------------- ### Configure Passive Health Checks in YAML Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/configuration.md Example YAML configuration for enabling and setting parameters for passive health checks. ```yaml health_checks: passive: enabled: true unhealthy_threshold: 3 unhealthy_timeout: 30 ``` -------------------------------- ### Implement Custom Plugin Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/plugins.md Register a custom middleware plugin using plugins.RegisterBuiltin and integrate it into the plugin chain. ```go package main import ( "net/http" "sync/atomic" "github.com/0xReLogic/Helios/internal/plugins" ) func init() { plugins.RegisterBuiltin("request_counter", func(name string, cfg map[string]interface{}) (plugins.Middleware, error) { // Simple counter middleware var count int64 return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Increment counter atomically current := atomic.AddInt64(&count, 1) // Add header with request number w.Header().Set("X-Request-Number", fmt.Sprintf("%d", current)) // Call next handler next.ServeHTTP(w, r) }) }, nil }) } func main() { // Register custom plugin, then use normally in config cfg := config.PluginsConfig{ Enabled: true, Chain: []config.PluginConfig{ {Name: "request_counter"}, }, } handler, _ := plugins.BuildChain(cfg, baseHandler) } ``` -------------------------------- ### Select Backend via NextBackend Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/load-balancing-strategies.md Method signature for selecting a backend based on the incoming HTTP request. ```go func (ih *IPHashStrategy) NextBackend(r *http.Request) *Backend ``` -------------------------------- ### Proxy Request via cURL Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/endpoints.md Example of sending a POST request to the proxy handler with custom headers and JSON payload. ```bash curl -X POST http://localhost:8080/api/users \ -H "Content-Type: application/json" \ -d '{"name": "John"}' \ -H "X-Trace-ID: trace123" ``` -------------------------------- ### Implement Plugin Unit Test in Go Source: https://github.com/0xrelogic/helios/blob/main/docs/plugin-development.md Uses httptest to simulate the middleware chain and verify plugin output. Requires the testing and net/http/httptest packages. ```go func TestMyPlugin(t *testing.T) { // 1. Create a mock 'next' HTTP handler // This handler simulates the behavior of the next component in the middleware chain // (e.g., another plugin or the backend service). handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // For this example, we simply write a 200 OK status. // In a real test, you might assert request headers, body, or path // that your plugin is expected to modify before passing it down. w.WriteHeader(http.StatusOK) }) // 2. Instantiate your plugin's middleware // Call your plugin's factory function with a test name and any required configuration. // The 'factory' function here is a placeholder for your actual plugin factory. mw, err := factory("test-plugin", map[string]interface{}{ // "configKey": "configValue", // Add any necessary plugin configuration }) if err != nil { t.Fatalf("failed to create plugin middleware: %v", err) } // 3. Prepare a test HTTP request and response recorder // `httptest.NewRequest` creates a synthetic incoming request. // `httptest.NewRecorder` captures the response written by your plugin. req := httptest.NewRequest("GET", "/test-path", nil) // Optionally, add headers or a body to the request if your plugin processes them. // req.Header.Set("X-Test-Header", "value") rec := httptest.NewRecorder() // 4. Execute the plugin middleware // Your plugin's middleware (mw) is applied to the mock handler. // The combined handler then serves the test request, writing to the recorder. mw(handler).ServeHTTP(rec, req) // 5. Assert the outcomes // Check the recorded response for expected status codes, headers, or body content. if rec.Code != http.StatusOK { t.Errorf("expected status %d, got %d", http.StatusOK, rec.Code) } // Example: Assert a header set by your plugin // if rec.Header().Get("X-Plugin-Header") != "expected-value" { // t.Errorf("expected X-Plugin-Header 'expected-value', got '%s'", rec.Header().Get("X-Plugin-Header")) // } } ``` -------------------------------- ### List Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/plugins.md Returns the names of available built-in plugins. ```APIDOC ## List() ### Description Returns the names of available built-in plugins. ### Returns - **[]string** - Plugin names ``` -------------------------------- ### Configuration Hierarchy Overview Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/types.md Visual representation of the project's configuration structure. ```text Config ├── Server (ServerConfig) │ ├── TLS (TLSConfig) │ └── Timeouts (TimeoutConfig) ├── Backends ([]BackendConfig) ├── LoadBalancer (LoadBalancerConfig) │ └── WebSocketPool (WebSocketPoolConfig) ├── HealthChecks (HealthChecksConfig) │ ├── Active (ActiveHealthCheckConfig) │ └── Passive (PassiveHealthCheckConfig) ├── RateLimit (RateLimitConfig) ├── CircuitBreaker (CircuitBreakerConfig) ├── Metrics (MetricsConfig) ├── AdminAPI (AdminAPIConfig) ├── Plugins (PluginsConfig) │ └── Chain ([]PluginConfig) └── Logging (LoggingConfig) ├── RequestID (RequestIDConfig) └── Trace (TraceConfig) ``` -------------------------------- ### Initialize RoundRobinStrategy Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/load-balancing-strategies.md Constructor for creating a new instance of the Round Robin strategy. ```go func NewRoundRobinStrategy() *RoundRobinStrategy ``` ```go strategy := loadbalancer.NewRoundRobinStrategy() ``` -------------------------------- ### Trigger Invalid JSON Error via cURL Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/errors.md Example of a 400 Bad Request response caused by malformed JSON in the request body. ```bash curl -X POST http://localhost:9091/v1/backends/add \ -H "Authorization: Bearer token" \ -H "Content-Type: application/json" \ -d '{invalid json}' # Returns 400 invalid json: invalid character 'i' looking for beginning of value ``` -------------------------------- ### Define Plugins Configuration Structures Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/configuration.md Go structures used to define the plugin system configuration and individual plugin settings. ```go type PluginsConfig struct { Enabled bool Chain []PluginConfig } type PluginConfig struct { Name string Config map[string]interface{} } ``` -------------------------------- ### Initialize IPHashStrategy Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/load-balancing-strategies.md Constructor function to create a new instance of the IP hash strategy. ```go func NewIPHashStrategy() *IPHashStrategy ``` ```go strategy := loadbalancer.NewIPHashStrategy() ``` -------------------------------- ### GET /metrics Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/metrics.md Serves Prometheus-compatible metrics for the Helios system, including request counts, response times, backend health, and circuit breaker states. ```APIDOC ## GET /metrics ### Description Returns an HTTP handler that serves Prometheus-compatible metrics. The output is formatted in the standard Prometheus text format with TYPE and HELP lines. ### Method GET ### Endpoint /metrics ### Response #### Success Response (200) - **Prometheus Metrics** (text/plain) - A collection of metrics including helios_requests_total, helios_response_time_ms, helios_backend_requests_total, and helios_circuit_breaker_state. ``` -------------------------------- ### NextBackend Method for Least Connections Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/load-balancing-strategies.md Method signature and algorithmic logic for selecting the backend with the fewest active connections. ```go func (lc *LeastConnectionsStrategy) NextBackend(r *http.Request) *Backend ``` ```text min_connections = MaxInt32 selected = nil for each backend: if backend.active_connections < min_connections: min_connections = backend.active_connections selected = backend return selected ``` ```go // Connections: server1=5, server2=2, server3=8 lc.NextBackend() // server2 (2 connections) lc.NextBackend() // server2 (now 3) lc.NextBackend() // server1 (now 6, tied with server2 at 3) ``` -------------------------------- ### Add Backend to Strategy Source: https://github.com/0xrelogic/helios/blob/main/_autodocs/api-reference/load-balancing-strategies.md Appends a new backend to the internal list for the current strategy. ```go func (s *Strategy) AddBackend(backend *Backend) ```