{"id":24953373,"url":"https://github.com/iamfarrokhnejad/load-balancer","last_synced_at":"2025-03-28T19:46:03.553Z","repository":{"id":258866119,"uuid":"875450344","full_name":"IAmFarrokhnejad/Load-Balancer","owner":"IAmFarrokhnejad","description":"A load balancer with round-robin algorithm using Go","archived":false,"fork":false,"pushed_at":"2024-10-28T22:53:09.000Z","size":11,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-03T03:35:01.354Z","etag":null,"topics":["functional","functional-programming","go","golang","server"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/IAmFarrokhnejad.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-10-20T02:30:21.000Z","updated_at":"2025-01-02T01:29:42.000Z","dependencies_parsed_at":"2024-10-22T03:13:52.920Z","dependency_job_id":null,"html_url":"https://github.com/IAmFarrokhnejad/Load-Balancer","commit_stats":null,"previous_names":["iamfarrokhnejad/load-balancer"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/IAmFarrokhnejad%2FLoad-Balancer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/IAmFarrokhnejad%2FLoad-Balancer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/IAmFarrokhnejad%2FLoad-Balancer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/IAmFarrokhnejad%2FLoad-Balancer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/IAmFarrokhnejad","download_url":"https://codeload.github.com/IAmFarrokhnejad/Load-Balancer/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246093097,"owners_count":20722395,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["functional","functional-programming","go","golang","server"],"created_at":"2025-02-03T03:35:31.984Z","updated_at":"2025-03-28T19:46:03.520Z","avatar_url":"https://github.com/IAmFarrokhnejad.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Simple Load Balancer with Reverse Proxy and Graceful Shutdown\n\nThis Go application implements a simple HTTP load balancer with round-robin load distribution, reverse proxying, logging middleware, and a graceful shutdown mechanism.\n\n## Features\n\n- **Round-Robin Load Balancing**: Distributes incoming HTTP requests across multiple backend servers in a round-robin manner.\n- **Health Checks**: Verifies server availability using `HEAD` requests to ensure only healthy servers receive traffic.\n- **Reverse Proxying**: Uses `httputil.ReverseProxy` to forward incoming requests to backend servers.\n- **Request Logging**: Logs each incoming request's HTTP method and path for easy monitoring.\n- **Graceful Shutdown**: Ensures a clean shutdown by listening for interrupt signals and allowing ongoing requests to complete.\n\n## Components\n\n### `simpleServer`\nRepresents a server instance that forwards incoming requests to a specified backend server. It performs health checks and proxies requests using `httputil.ReverseProxy`.\n\n#### Methods\n- `Address()`: Returns the server's address.\n- `IsAlive()`: Checks server health by sending a `HEAD` request.\n- `Serve()`: Forwards requests to the backend server.\n\n### `LoadBalancer`\nManages a list of servers, selecting a healthy server in round-robin fashion for each incoming request.\n\n#### Methods\n- `getNextAvailableServer()`: Returns the next available and healthy server.\n- `serveProxy()`: Selects a server and forwards the request to it.\n\n### Middleware\n- **Logging Middleware**: Logs each request to standard output.\n\n## Usage\n\n1. **Define Servers**: Specify backend server URLs by creating `simpleServer` instances.\n2. **Initialize Load Balancer**: Instantiate a `LoadBalancer` with a list of servers.\n3. **Run Server**: Start the HTTP server on the specified port (`8000` by default) with graceful shutdown support.\n\n## Graceful Shutdown\nThe server listens for an interrupt signal (e.g., `Ctrl+C`) and initiates a shutdown sequence that waits up to 5 seconds for in-progress requests to complete.\n\n## Code Example\n\n```go\npackage main\n\n// Main entry point of the application\nfunc main() {\n    // Define backend servers\n    servers := []Server{\n        newSimpleServer(\"https://www.example.com\"),\n        newSimpleServer(\"https://www.bing.com\"),\n        newSimpleServer(\"https://www.google.com\"),\n    }\n\n    // Initialize load balancer\n    lb := NewLoadBalancer(\"8000\", servers)\n\n    // Define HTTP handler\n    handleRedirect := func(rw http.ResponseWriter, req *http.Request) {\n        lb.serveProxy(rw, req)\n    }\n\n    // Setup server and graceful shutdown\n    mux := http.NewServeMux()\n    mux.HandleFunc(\"/\", handleRedirect)\n    loggedMux := loggingMiddleware(mux)\n\n    srv := \u0026http.Server{\n        Addr:    \":8000\",\n        Handler: loggedMux,\n    }\n\n    // Start server\n    go func() {\n        fmt.Printf(\"Serving requests at 'localhost:%s'\\n\", lb.port)\n        if err := srv.ListenAndServe(); err != nil \u0026\u0026 err != http.ErrServerClosed {\n            handleErr(err)\n        }\n    }()\n\n    // Graceful shutdown logic\n    stop := make(chan os.Signal, 1)\n    signal.Notify(stop, os.Interrupt)\n    \u003c-stop\n    fmt.Println(\"\\nShutting down the server...\")\n\n    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n    defer cancel()\n\n    if err := srv.Shutdown(ctx); err != nil {\n        fmt.Printf(\"Shutdown error: %v\\n\", err)\n    } else {\n        fmt.Println(\"Server gracefully stopped.\")\n    }\n}\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fiamfarrokhnejad%2Fload-balancer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fiamfarrokhnejad%2Fload-balancer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fiamfarrokhnejad%2Fload-balancer/lists"}