racer: refactor. no hard code, don't repeat
This commit is contained in:
parent
3cc29f8383
commit
ee89092ea4
@ -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
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -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")
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user