The following setup uses a select statement to either wait for a response 
error or timeout after a given duration.

The httptest.Server is setup to force the timeout by sleeping (1 sec) for 
greater than the timeout (1 millisec).

But the timeout case isn't being hit at all, why? what is wrong with the 
setup?

https://play.golang.org/p/jX_nZPV4vVY

package main

import (
"fmt"
"time"
"net/http"
"net/http/httptest"
"errors"
)

func main() {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r 
*http.Request) {
time.Sleep(1 * time.Second)
w.WriteHeader(http.StatusOK)
}))
defer ts.Close()

req, _ := http.NewRequest(http.MethodGet, ts.URL, nil)
f := func(r *http.Request) error {
_, err := http.DefaultClient.Do(r)
return err
}
ch := make(chan error, 1)
timeout := 1 * time.Millisecond
select {
case ch <-f(req):
case <-time.After(timeout):
ch <- errors.New("timeout")
}
err:= <-ch
close(ch)
fmt.Println(err) // outputs <nil>, not timeout
// Output:
// timeout
}


-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to