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
+7.2k Golang : File system scanning
+35.7k Golang : Integer is between a range
+6.4k Golang : Handling image beyond OpenCV video capture boundary
+4.9k Golang : micron to centimeter example
+28.5k Get file path of temporary file in Go
+12.3k Golang : Search and extract certain XML data example
+17.6k Golang : Upload/Receive file progress indicator
+37.4k Upload multiple files with Go
+15.2k Golang : Get all local users and print out their home directory, description and group id
+5.3k Unix/Linux : How to archive and compress entire directory ?
+11k Golang : Create S3 bucket with official aws-sdk-go package