racer: refactor. no hard code, don't repeat

This commit is contained in:
vinchent 2024-09-18 13:11:42 +02:00
parent 3cc29f8383
commit ee89092ea4
2 changed files with 7 additions and 5 deletions

View File

@ -6,15 +6,17 @@ import (
"time"
)
func Racer(a, b string) (string, error) {
var ErrRacerTimeout = errors.New("timeout")
func Racer(a, b string, timeout time.Duration) (string, error) {
select {
// wait until channel closed
case <-ping(a):
return a, nil
case <-ping(b):
return b, nil
case <-time.After(10 * time.Second):
return "", errors.New("timeout")
case <-time.After(timeout):
return "", ErrRacerTimeout
}
}

View File

@ -19,7 +19,7 @@ func TestRacer(t *testing.T) {
fastURL := fastServer.URL
want := fastURL
got, _ := Racer(slowURL, fastURL)
got, _ := Racer(slowURL, fastURL, 10*time.Second)
if got != want {
t.Errorf("got %q, want %q", got, want)
@ -33,7 +33,7 @@ func TestRacer(t *testing.T) {
serverB := makeDelayedServer(11 * time.Second)
defer serverB.Close()
_, err := Racer(serverA.URL, serverB.URL)
_, err := Racer(serverA.URL, serverB.URL, 10*time.Second)
if err == nil {
t.Error("expected an error but didn't got one")
}