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" "time"
) )
func Racer(a, b string) (string, error) { var ErrRacerTimeout = errors.New("timeout")
func Racer(a, b string, timeout time.Duration) (string, error) {
select { select {
// wait until channel closed // wait until channel closed
case <-ping(a): case <-ping(a):
return a, nil return a, nil
case <-ping(b): case <-ping(b):
return b, nil return b, nil
case <-time.After(10 * time.Second): case <-time.After(timeout):
return "", errors.New("timeout") return "", ErrRacerTimeout
} }
} }

View File

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