racer: use select to syncrho

This commit is contained in:
vinchent 2024-09-18 12:58:07 +02:00
parent 5042f1048e
commit 2dc7275f15

View File

@ -7,13 +7,13 @@ 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
}
return b
}
func measureResponseTime(url string) time.Duration {
@ -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
}