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 {
|
||||
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
|
||||
}
|
||||
|
@ -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)
|
||||
}))
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user