2024-09-18 08:15:53 +00:00
|
|
|
package racer
|
|
|
|
|
|
|
|
import (
|
2024-09-18 11:08:31 +00:00
|
|
|
"errors"
|
2024-09-18 08:15:53 +00:00
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2024-09-18 11:11:42 +00:00
|
|
|
var ErrRacerTimeout = errors.New("timeout")
|
|
|
|
|
2024-09-18 11:41:55 +00:00
|
|
|
const tenSecondTimeout = 10 * time.Second
|
|
|
|
|
|
|
|
func ConfigurableRacer(a, b string, timeout time.Duration) (string, error) {
|
2024-09-18 10:58:07 +00:00
|
|
|
select {
|
|
|
|
// wait until channel closed
|
|
|
|
case <-ping(a):
|
2024-09-18 11:08:31 +00:00
|
|
|
return a, nil
|
2024-09-18 10:58:07 +00:00
|
|
|
case <-ping(b):
|
2024-09-18 11:08:31 +00:00
|
|
|
return b, nil
|
2024-09-18 11:11:42 +00:00
|
|
|
case <-time.After(timeout):
|
|
|
|
return "", ErrRacerTimeout
|
2024-09-18 08:15:53 +00:00
|
|
|
}
|
|
|
|
}
|
2024-09-18 10:54:47 +00:00
|
|
|
|
2024-09-18 11:41:55 +00:00
|
|
|
func Racer(a, b string) (string, error) {
|
|
|
|
return ConfigurableRacer(a, b, tenSecondTimeout)
|
|
|
|
}
|
|
|
|
|
2024-09-18 10:58:07 +00:00
|
|
|
func ping(url string) chan struct{} {
|
|
|
|
ch := make(chan struct{})
|
|
|
|
go func() {
|
|
|
|
http.Get(url)
|
|
|
|
// if got, close channel
|
|
|
|
close(ch)
|
|
|
|
}()
|
|
|
|
return ch
|
|
|
|
}
|
2024-09-18 11:08:31 +00:00
|
|
|
|
|
|
|
// func measureResponseTime(url string) time.Duration {
|
|
|
|
// start := time.Now()
|
|
|
|
// http.Get(url)
|
|
|
|
// duration := time.Since(start)
|
|
|
|
// fmt.Println(duration)
|
|
|
|
// return duration
|
|
|
|
// }
|