Timeout for a connection to an external resource, or some other program in terms of the time it takes to perform the operation is very important. Thanks to the channel and select
achieve operation timeout in Go is simple and elegant.
Example:
main Package Import " FMT " Import " Time " FUNC main () { c1: = the make (Chan String) // In our example, if we execute an external call, and 2 back through the passage c1 seconds after its execution result. FUNC Go () { time.sleep (time.Second * 2 ) C1 <- " One " } () // this is implemented using a select operation timeout. res: = <- c1 wait for the results, <- Time.After 1 wait timeout value after the second transmission. // Since select the default handler is ready to receive the first operation, if the operation exceeds the allowable 1 second, it will timeout case. {SELECT Case RES: = <- C1: fmt.Println (RES) Case<- time.After(time.Second * 1): fmt.Println("timeout 1") } c2 := make(chan string) go func(){ time.Sleep(time.Second * 2) c2 <- "two" }() select{ case res := <-c2: fmt.Println(res) case <- time.After(time.Second * 3): fmt.Println("timeount 2") } }
Result:
$ go run example.go
timeout 1
two
Run the program, first time out of the show running operation, and then successfully received.
Use this select
timeout mode, the results need to pass the channel. This is a good way for the general case, because other important feature is based on channel and Go select
's.