From 9a7270d2f92a86208404fbe8db670a53c50b5509 Mon Sep 17 00:00:00 2001 From: Quaternions Date: Sun, 15 Dec 2024 03:20:22 -0800 Subject: [PATCH] submissions: chatgpt solution #2 --- pkg/cmds/serve.go | 36 ++++++++++++++++-------------------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/pkg/cmds/serve.go b/pkg/cmds/serve.go index 40ce732..690d553 100644 --- a/pkg/cmds/serve.go +++ b/pkg/cmds/serve.go @@ -3,7 +3,6 @@ package cmds import ( "fmt" "net/http" - "sync" "git.itzana.me/strafesnet/go-grpc/auth" "git.itzana.me/strafesnet/maps-service/pkg/api" @@ -138,30 +137,27 @@ func serve(ctx *cli.Context) error { if err != nil { log.WithError(err).Fatal("failed to initialize api server") } - - var wg sync.WaitGroup - wg.Add(2) // We'll wait for two goroutines, one for each server. + // Channel to collect errors + errChan := make(chan error, 2) // First server - go func() { - defer wg.Done() - err := http.ListenAndServe(fmt.Sprintf(":%d", ctx.Int("port-internal")), srv2) - if err != nil { - log.Printf("Internal server error: %v", err) - } - }() + go func(errChan chan error) { + errChan <- http.ListenAndServe(fmt.Sprintf(":%d", ctx.Int("port-internal")), srv2) + }(errChan) // Second server - go func() { - defer wg.Done() - err := http.ListenAndServe(fmt.Sprintf(":%d", ctx.Int("port")), srv) - if err != nil { - log.Printf("External server error: %v", err) - } - }() + go func(errChan chan error) { + errChan <- http.ListenAndServe(fmt.Sprintf(":%d", ctx.Int("port")), srv) + }(errChan) - // Wait for both servers to finish. - wg.Wait() + // Wait for the first error or completion of both tasks + for i := 0; i < 2; i++ { + err := <-errChan + if err != nil { + fmt.Println("Exiting due to:", err) + return err + } + } log.Println("Both servers have stopped.") return nil