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}
package main
import ( "errors" "fmt" "net/http" "net/http/httptest" "time"
)
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, n int) error { fmt.Println("Making the http call ", n)
timeout := 1 * time.Millisecond select {
case ch <- errors.New("immediate timeout"): case ch <- f(req, 1): case ch <- f(req, 2): case <-time.After(timeout): fmt.Println("Timeout being called")
ch <- errors.New("timeout") }
err1 := <-ch fmt.Println("Received first error", err1) close(ch)
// Output: // Making the http call 1
// Making the http call 2
// Received first error immediate timeout
}
Execution of a "select" statement proceeds in several steps:
- For all the cases in the statement, the channel operands of receive operations and the channel and right-hand-side expressions of send statements are evaluated exactly once, in source order, upon entering the "select" statement. The result is a set of channels to receive from or send to, and the corresponding values to send. Any side effects in that evaluation will occur irrespective of which (if any) communication operation is selected to proceed. Expressions on the left-hand side of a RecvStmt with a short variable declaration or assignment are not yet evaluated.
- If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection. Otherwise, if there is a default case, that case is chosen. If there is no default case, the "select" statement blocks until at least one of the communications can proceed.
- Unless the selected case is the default case, the respective communication operation is executed.
- If the selected case is a RecvStmt with a short variable declaration or an assignment, the left-hand side expressions are evaluated and the received value (or values) are assigned.
- The statement list of the selected case is executed.