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
+10.3k Golang : Get local time and equivalent time in different time zone
+11.2k Golang : Find age or leap age from date of birth example
+9.4k Golang : Populate slice with sequential integers example
+29.5k Golang : How to declare kilobyte, megabyte, gigabyte, terabyte and so on?
+33.7k Golang : Call a function after some delay(time.Sleep and Tick)
+6.9k Golang : Validate credit card example
+14.4k Golang : Get URI segments by number and assign as variable example
+16.6k Golang : How to generate QR codes?
+4.6k Javascript : How to get width and height of a div?
+13.5k Golang : Get dimension(width and height) of image file
+9.4k Random number generation with crypto/rand in Go
+7k Golang : How to iterate a slice without using for loop?