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,14 +7,14 @@ import (
) )
func Racer(a, b string) string { func Racer(a, b string) string {
aDuration := measureResponseTime(a) select {
bDuration := measureResponseTime(b) // wait until channel closed
case <-ping(a):
if aDuration < bDuration {
return a return a
} case <-ping(b):
return b return b
} }
}
func measureResponseTime(url string) time.Duration { func measureResponseTime(url string) time.Duration {
start := time.Now() start := time.Now()
@ -23,3 +23,13 @@ func measureResponseTime(url string) time.Duration {
fmt.Println(duration) fmt.Println(duration)
return 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
}