From 5042f1048eebae509ca76f5a7837b64eefbfda7a Mon Sep 17 00:00:00 2001 From: vinchent Date: Wed, 18 Sep 2024 12:54:47 +0200 Subject: [PATCH] racer: refactor code to not repeat --- racer/racer.go | 18 ++++++++++-------- racer/racer_test.go | 19 ++++++++++--------- 2 files changed, 20 insertions(+), 17 deletions(-) diff --git a/racer/racer.go b/racer/racer.go index 8927c2e..679957b 100644 --- a/racer/racer.go +++ b/racer/racer.go @@ -7,17 +7,19 @@ import ( ) func Racer(a, b string) string { - startA := time.Now() - http.Get(a) - aDuration := time.Since(startA) - fmt.Println(aDuration) + aDuration := measureResponseTime(a) + bDuration := measureResponseTime(b) - startB := time.Now() - http.Get(b) - bDuration := time.Since(startB) - fmt.Println(bDuration) if aDuration < bDuration { return a } return b } + +func measureResponseTime(url string) time.Duration { + start := time.Now() + http.Get(url) + duration := time.Since(start) + fmt.Println(duration) + return duration +} diff --git a/racer/racer_test.go b/racer/racer_test.go index 07f29c7..1815334 100644 --- a/racer/racer_test.go +++ b/racer/racer_test.go @@ -8,17 +8,10 @@ import ( ) func TestRacer(t *testing.T) { - slowServer := httptest.NewServer(http.HandlerFunc( - func(w http.ResponseWriter, r *http.Request) { - time.Sleep(20 * time.Millisecond) - w.WriteHeader(http.StatusOK) - })) + slowServer := makeDelayedServer(20 * time.Millisecond) defer slowServer.Close() - fastServer := httptest.NewServer(http.HandlerFunc( - func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - })) + fastServer := makeDelayedServer(0 * time.Millisecond) defer fastServer.Close() slowURL := slowServer.URL @@ -31,3 +24,11 @@ func TestRacer(t *testing.T) { t.Errorf("got %q, want %q", got, want) } } + +func makeDelayedServer(delay time.Duration) *httptest.Server { + return httptest.NewServer(http.HandlerFunc( + func(w http.ResponseWriter, r *http.Request) { + time.Sleep(delay) + w.WriteHeader(http.StatusOK) + })) +}