go-by-test/racer/racer.go

46 lines
822 B
Go

package racer
import (
"errors"
"net/http"
"time"
)
var ErrRacerTimeout = errors.New("timeout")
const tenSecondTimeout = 10 * time.Second
func ConfigurableRacer(a, b string, timeout time.Duration) (string, error) {
select {
// wait until channel closed
case <-ping(a):
return a, nil
case <-ping(b):
return b, nil
case <-time.After(timeout):
return "", ErrRacerTimeout
}
}
func Racer(a, b string) (string, error) {
return ConfigurableRacer(a, b, tenSecondTimeout)
}
func ping(url string) chan struct{} {
ch := make(chan struct{})
go func() {
http.Get(url)
// if got, close channel
close(ch)
}()
return ch
}
// func measureResponseTime(url string) time.Duration {
// start := time.Now()
// http.Get(url)
// duration := time.Since(start)
// fmt.Println(duration)
// return duration
// }