submissions: chatgpt solution #2
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Quaternions 2024-12-15 03:20:22 -08:00
parent cb736628d7
commit 9a7270d2f9

View File

@ -3,7 +3,6 @@ package cmds
import ( import (
"fmt" "fmt"
"net/http" "net/http"
"sync"
"git.itzana.me/strafesnet/go-grpc/auth" "git.itzana.me/strafesnet/go-grpc/auth"
"git.itzana.me/strafesnet/maps-service/pkg/api" "git.itzana.me/strafesnet/maps-service/pkg/api"
@ -138,30 +137,27 @@ func serve(ctx *cli.Context) error {
if err != nil { if err != nil {
log.WithError(err).Fatal("failed to initialize api server") log.WithError(err).Fatal("failed to initialize api server")
} }
// Channel to collect errors
var wg sync.WaitGroup errChan := make(chan error, 2)
wg.Add(2) // We'll wait for two goroutines, one for each server.
// First server // First server
go func() { go func(errChan chan error) {
defer wg.Done() errChan <- http.ListenAndServe(fmt.Sprintf(":%d", ctx.Int("port-internal")), srv2)
err := http.ListenAndServe(fmt.Sprintf(":%d", ctx.Int("port-internal")), srv2) }(errChan)
if err != nil {
log.Printf("Internal server error: %v", err)
}
}()
// Second server // Second server
go func() { go func(errChan chan error) {
defer wg.Done() errChan <- http.ListenAndServe(fmt.Sprintf(":%d", ctx.Int("port")), srv)
err := http.ListenAndServe(fmt.Sprintf(":%d", ctx.Int("port")), srv) }(errChan)
if err != nil {
log.Printf("External server error: %v", err)
}
}()
// Wait for both servers to finish. // Wait for the first error or completion of both tasks
wg.Wait() 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.") log.Println("Both servers have stopped.")
return nil return nil