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
+25.3k Golang : Convert CSV data to JSON format and save to file
+28.2k Golang : How to get HTTP request header information?
+6.3k Golang : Convert source code to assembly language
+6.8k Golang : Oanda bot with Telegram and RSI example
+43.8k Golang : Encode image to base64 example
+15.4k Golang : Check if IP address is version 4 or 6
+7.9k Golang : Read file with ioutil
+4.1k Golang : Return multiple values from function
+6.3k Golang : Generate human readable password
+12.9k Golang : Get URI segments by number and assign as variable example
+4.5k List of Golang XML tutorials
+26.4k Golang : Connect to database (MySQL/MariaDB) server