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
+5.6k Golang : Markov chains to predict probability of next state example
+10.7k Golang : Natural string sorting example
+11.4k Golang : Calculations using complex numbers example
+6.6k Mac OSX : Find large files by size
+9.4k Javascript : Read/parse JSON data from HTTP response
+35.6k Golang : Get file last modified date and time
+4.4k Linux : sudo yum updates not working
+14.6k Golang : Basic authentication with .htpasswd file
+31.2k Golang : Get local IP and MAC address
+4.3k Javascript : Detect when console is activated and do something about it
+39.8k Golang : Convert to io.ReadSeeker type
+7.2k Golang : Check to see if *File is a file or directory