racer: use select to syncrho
This commit is contained in:
parent
5042f1048e
commit
2dc7275f15
@ -7,14 +7,14 @@ import (
|
||||
)
|
||||
|
||||
func Racer(a, b string) string {
|
||||
aDuration := measureResponseTime(a)
|
||||
bDuration := measureResponseTime(b)
|
||||
|
||||
if aDuration < bDuration {
|
||||
select {
|
||||
// wait until channel closed
|
||||
case <-ping(a):
|
||||
return a
|
||||
}
|
||||
case <-ping(b):
|
||||
return b
|
||||
}
|
||||
}
|
||||
|
||||
func measureResponseTime(url string) time.Duration {
|
||||
start := time.Now()
|
||||
@ -23,3 +23,13 @@ func measureResponseTime(url string) time.Duration {
|
||||
fmt.Println(duration)
|
||||
return duration
|
||||
}
|
||||
|
||||
func ping(url string) chan struct{} {
|
||||
ch := make(chan struct{})
|
||||
go func() {
|
||||
http.Get(url)
|
||||
// if got, close channel
|
||||
close(ch)
|
||||
}()
|
||||
return ch
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user