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
+4.3k Golang : List all packages and search for certain package
+7.6k Golang : Use regular expression to get all upper case or lower case characters example
+8.5k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+21.4k Golang : Create PDF file from HTML file
+6.4k Golang : Detect Pascal, Kebab, Screaming Snake and Camel cases
+10.9k Golang : Drop cookie to visitor's browser and http.SetCookie() example
+8.2k Golang : Fix - does not implement sort.Interface (missing Len method)
+15.9k Golang : Padding data for encryption and un-padding data for decryption
+32.1k Golang : Read a text file and replace certain words
+10.5k Golang : convert(cast) string to integer value
+14.5k Golang : Get download file size
+8.1k Javascript : Read/parse JSON data from HTTP response