From dcc3cfa44f0173c58f9714c4c631f2ee3eb3a471 Mon Sep 17 00:00:00 2001 From: Paul Brinkmeier Date: Fri, 25 Apr 2025 12:30:19 +0200 Subject: [PATCH] Send requests to different servers using round-robin --- main.go | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/main.go b/main.go index 44a2b9b..967b8e2 100644 --- a/main.go +++ b/main.go @@ -10,6 +10,7 @@ import "os" import "slices" import "strings" import "strconv" +import "sync/atomic" import "time" // JSON unmarshaling types for departure monitor API @@ -110,8 +111,7 @@ func (c KVVEFAClient) BuildRequest(stopId string) (*http.Request, error) { return req, nil } -func FetchDepartures(stopId string) (DMResponse, error) { - var c EFAClient = KVVEFAClient{} +func FetchDepartures(c EFAClient, stopId string) (DMResponse, error) { req, err := c.BuildRequest(stopId) if err != nil { return DMResponse{}, err @@ -203,6 +203,13 @@ func main() { panic("Required environment variable VRNP_PASSWORD is not set") } + // Use round-robin to send incoming requests to different servers + var efaClient atomic.Uint64 + efaClients := []EFAClient{ + VRNEFAClient{}, + KVVEFAClient{}, + } + http.HandleFunc("/departures", func(w http.ResponseWriter, r *http.Request) { user, pass, ok := r.BasicAuth() if !(ok && user == "admin" && pass == password) { @@ -224,7 +231,8 @@ func main() { platform = &query["platform"][0] } - ds, err := FetchDepartures(stopId) + c := efaClients[(efaClient.Add(1) - 1) % uint64(len(efaClients))] + ds, err := FetchDepartures(c, stopId) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return