go-by-test/racer/racer.go

38 lines
619 B
Go
Raw Normal View History

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:08:31 +00:00
func Racer(a, b string) (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
case <-time.After(10 * time.Second):
return "", errors.New("timeout")
2024-09-18 08:15:53 +00:00
}
}
2024-09-18 10:54:47 +00:00
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
// }