From 215018850114cf4034e52dc6c7a2dedd03e48126 Mon Sep 17 00:00:00 2001 From: Drew Bednar Date: Wed, 21 Aug 2024 17:21:08 -0400 Subject: [PATCH] racer --- learn_go_with_tests/my_select/go.mod | 3 ++ learn_go_with_tests/my_select/racer.go | 23 ++++++++++++++ learn_go_with_tests/my_select/racer_test.go | 34 +++++++++++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 learn_go_with_tests/my_select/go.mod create mode 100644 learn_go_with_tests/my_select/racer.go create mode 100644 learn_go_with_tests/my_select/racer_test.go diff --git a/learn_go_with_tests/my_select/go.mod b/learn_go_with_tests/my_select/go.mod new file mode 100644 index 0000000..696d9bc --- /dev/null +++ b/learn_go_with_tests/my_select/go.mod @@ -0,0 +1,3 @@ +module my_select + +go 1.22.5 diff --git a/learn_go_with_tests/my_select/racer.go b/learn_go_with_tests/my_select/racer.go new file mode 100644 index 0000000..43b89d8 --- /dev/null +++ b/learn_go_with_tests/my_select/racer.go @@ -0,0 +1,23 @@ +package my_select + +import ( + "net/http" + "time" +) + +func Racer(a string, b string) (winner string) { + aDuration := measureResponseTime(a) + bDuration := measureResponseTime(b) + + if aDuration < bDuration { + return a + } + + return b +} + +func measureResponseTime(url string) time.Duration { + start := time.Now() + http.Get(url) + return time.Since(start) +} diff --git a/learn_go_with_tests/my_select/racer_test.go b/learn_go_with_tests/my_select/racer_test.go new file mode 100644 index 0000000..d5d27a3 --- /dev/null +++ b/learn_go_with_tests/my_select/racer_test.go @@ -0,0 +1,34 @@ +package my_select + +import ( + "net/http" + "net/http/httptest" + "testing" + "time" +) + +func TestRacer(t *testing.T) { + + slowServer := makeDelayedServer(20 * time.Microsecond) + defer slowServer.Close() + + fastServer := makeDelayedServer(0 * time.Microsecond) + defer fastServer.Close() + + slowUrl := slowServer.URL + fastUrl := fastServer.URL + + want := fastUrl + got := Racer(slowUrl, fastUrl) + + if got != want { + 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) + })) +}