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
+15.9k Golang : Get file permission
+14.5k Golang : Convert(cast) int to float example
+4.2k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example
+10.5k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
+21.1k Golang : How to force compile or remove object files first before rebuild?
+12.2k Golang : calculate elapsed run time
+7.5k Golang : Dealing with struct's private part
+4.6k Chrome : How to block socketloop.com links in Google SERP?
+10.2k Golang : Random Rune generator
+8.1k Golang : Get final or effective URL with Request.URL example
+44.8k Golang : Use wildcard patterns with filepath.Glob() example
+12.6k Golang : Pass database connection to function called from another package and HTTP Handler