Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get Timeout
package main
import (
"errors"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func main() {
tests := []testing.InternalTest{{"TestTimeoutGetter", TestTimeoutGetter}}
matchAll := func(t string, pat string) (bool, error) { return true, nil }
testing.Main(matchAll, tests, nil, nil)
}
type httpGetter struct {
transport *http.Transport
timeout time.Duration
}
func (h httpGetter) Get(url string) (*http.Response, error) {
var resp *http.Response
req, err := http.NewRequest("GET", url, nil)
defer h.transport.CancelRequest(req)
done := make(chan struct{}, 1)
go func() {
defer close(done)
resp, err = h.transport.RoundTrip(req)
done <- struct{}{}
}()
select {
case <-done:
return resp, err
case <-time.After(h.timeout):
return nil, errors.New("Probe timed out waiting for responseresponse timed out:")
}
}
func TestTimeoutGetter(t *testing.T) {
transport := &http.Transport{}
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(1 * time.Hour)
w.Write([]byte("bye"))
}))
for i := 0; i < 500; i++ {
_, err := httpGetter{transport, 1 * time.Millisecond}.Get(ts.URL)
if err == nil {
t.Error("should have seen a timeout error")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment