racer: refactor code to not repeat
This commit is contained in:
parent
3538818769
commit
5042f1048e
@ -7,17 +7,19 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func Racer(a, b string) string {
|
func Racer(a, b string) string {
|
||||||
startA := time.Now()
|
aDuration := measureResponseTime(a)
|
||||||
http.Get(a)
|
bDuration := measureResponseTime(b)
|
||||||
aDuration := time.Since(startA)
|
|
||||||
fmt.Println(aDuration)
|
|
||||||
|
|
||||||
startB := time.Now()
|
|
||||||
http.Get(b)
|
|
||||||
bDuration := time.Since(startB)
|
|
||||||
fmt.Println(bDuration)
|
|
||||||
if aDuration < bDuration {
|
if aDuration < bDuration {
|
||||||
return a
|
return a
|
||||||
}
|
}
|
||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func measureResponseTime(url string) time.Duration {
|
||||||
|
start := time.Now()
|
||||||
|
http.Get(url)
|
||||||
|
duration := time.Since(start)
|
||||||
|
fmt.Println(duration)
|
||||||
|
return duration
|
||||||
|
}
|
||||||
|
@ -8,17 +8,10 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func TestRacer(t *testing.T) {
|
func TestRacer(t *testing.T) {
|
||||||
slowServer := httptest.NewServer(http.HandlerFunc(
|
slowServer := makeDelayedServer(20 * time.Millisecond)
|
||||||
func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
time.Sleep(20 * time.Millisecond)
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
}))
|
|
||||||
defer slowServer.Close()
|
defer slowServer.Close()
|
||||||
|
|
||||||
fastServer := httptest.NewServer(http.HandlerFunc(
|
fastServer := makeDelayedServer(0 * time.Millisecond)
|
||||||
func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
}))
|
|
||||||
defer fastServer.Close()
|
defer fastServer.Close()
|
||||||
|
|
||||||
slowURL := slowServer.URL
|
slowURL := slowServer.URL
|
||||||
@ -31,3 +24,11 @@ func TestRacer(t *testing.T) {
|
|||||||
t.Errorf("got %q, want %q", 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)
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user