select
This commit is contained in:
parent
06dcef8884
commit
95928c5a76
24
select/racer.go
Normal file
24
select/racer.go
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
package racer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Racer(a, b string) (winner string) {
|
||||||
|
select {
|
||||||
|
case <-ping(a):
|
||||||
|
return a
|
||||||
|
case <-ping(b):
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
func ping(url string) chan struct{} {
|
||||||
|
ch := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
http.Get(url)
|
||||||
|
close(ch)
|
||||||
|
}()
|
||||||
|
return ch
|
||||||
|
}
|
34
select/racer_test.go
Normal file
34
select/racer_test.go
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
package racer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRacer(t *testing.T) {
|
||||||
|
slowServer := makeDelayedServer(20 * time.Millisecond)
|
||||||
|
fastServer := makeDelayedServer(0 * time.Millisecond)
|
||||||
|
|
||||||
|
defer slowServer.Close()
|
||||||
|
defer fastServer.Close()
|
||||||
|
|
||||||
|
slowURL := slowServer.URL
|
||||||
|
fastURL := fastServer.URL
|
||||||
|
|
||||||
|
want := fastURL
|
||||||
|
got := Racer(slowURL, fastURL)
|
||||||
|
|
||||||
|
if 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…
x
Reference in New Issue
Block a user