diff --git a/main.go b/main.go index 0e43718..a59f5fa 100644 --- a/main.go +++ b/main.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "log/slog" "net/http" "os" "strings" @@ -38,12 +39,7 @@ func measureLatency(url string) (time.Duration, error) { return time.Since(start), nil } -func main() { - maybePool := os.Getenv("POOL") - pool := DEFAULT_POOL - if maybePool != "" { - pool = strings.Split(maybePool, ",") - } +func findBestUpstream(pool []string) (string, error) { // Measure latency concurrently results := make(chan latencyResult, len(pool)) @@ -65,13 +61,14 @@ func main() { var best latencyResult best.latency = time.Hour // Start with a very high latency - fmt.Println("Latency results:") + slog.Debug("Latency results:") + var err error for result := range results { if result.err != nil { - fmt.Printf(" %s: ERROR - %v\n", result.url, result.err) + slog.Debug("connection error", slog.String("url", result.url), slog.Any("error", result.err)) continue } - fmt.Printf(" %s: %v\n", result.url, result.latency) + slog.Debug("latency measured", slog.String("url", result.url), slog.Duration("latency", result.latency)) if result.latency < best.latency { best = result @@ -79,8 +76,30 @@ func main() { } if best.err == nil && best.latency < time.Hour { - fmt.Printf("\nBest connection: %s (latency: %v)\n", best.url, best.latency) + slog.Debug("Best connection", slog.String("url", best.url), slog.Duration("latency", best.latency)) + return best.url, nil } else { - fmt.Println("\nNo valid connections found") + slog.Debug("No valid connections found") + return "", err } + +} + +func main() { + maybePool := os.Getenv("POOL") + pool := DEFAULT_POOL + if maybePool != "" { + pool = strings.Split(maybePool, ",") + } + + if os.Getenv("DEBUG") == "1" { + slog.SetLogLoggerLevel(slog.LevelDebug) + } + + bestUpstream, err := findBestUpstream(pool) + if err != nil { + panic(err) + } + + fmt.Println(bestUpstream) }