Golang : Timeout example
It is important for programs to know when to abort when connecting to external resources. One such example is the net.DialTimeout()
function and if you looking to implement timeout feature in Golang, it is pretty easy with channels and select.
This code example below simulates a situation when a timeout occurred.
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan bool, 1)
go func() {
select {
case m := <-c:
// do something
handle(m)
case <-time.After(3 * time.Second):
fmt.Println("timed out")
}
}()
time.Sleep(5 * time.Second)
}
func handle(m bool) {}
References :
See also : Golang : Call a function after some delay(time.Sleep and Tick)
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+22.4k Golang : How to run Golang application such as web server in the background or as daemon?
+41.6k Golang : Convert string to array/slice
+6.5k PHP : How to handle URI or URL with non-ASCII characters such as Chinese/Japanese/Korean(CJK) ?
+11.3k Google Maps URL parameters configuration
+8.3k Golang : Multiplexer with net/http and map
+4.8k Linux : sudo yum updates not working
+16.6k Golang : Loop each day of the current month example
+10.3k Golang : Edge detection with Sobel method
+14.7k Golang : Overwrite previous output with count down timer
+28.4k Golang : Connect to database (MySQL/MariaDB) server
+7.7k SSL : How to check if current certificate is sha1 or sha2 from command line
+83k Golang : How to return HTTP status code?