Timeouts are important for programs that connect to
external resources or that otherwise need to bound
execution time. Implementing timeouts in Go is easy and
elegant thanks to channels and |
|
package main
|
|
import "time"
import "fmt"
|
|
func main() {
|
|
For our example, suppose we’re executing an external
call that returns its result on a channel |
c1 := make(chan string, 1)
go func() {
time.Sleep(time.Second * 2)
c1 <- "result 1"
}()
|
Here’s the |
select {
case res := <-c1:
fmt.Println(res)
case <-time.After(time.Second * 1):
fmt.Println("timeout 1")
}
|
If we allow a longer timeout of 3s, then the receive
from |
c2 := make(chan string, 1)
go func() {
time.Sleep(time.Second * 2)
c2 <- "result 2"
}()
select {
case res := <-c2:
fmt.Println(res)
case <-time.After(time.Second * 3):
fmt.Println("timeout 2")
}
}
|
Running this program shows the first operation timing out and the second succeeding. |
$ go run timeouts.go
timeout 1
result 2
|
Using this |
Next example: Non-Blocking Channel Operations.