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
+8.3k Golang : Metaprogramming example of wrapping a function
+24.2k Golang : Upload to S3 with official aws-sdk-go package
+8.1k Golang : Grayscale Image
+18.8k Golang : convert int to string
+7.6k Golang : Create zip/ePub file without compression(use Store algorithm)
+6.6k Golang : Map within a map example
+15.2k Golang : Search folders for file recursively with wildcard support
+5.8k Linux/Unix/PHP : Restart PHP-FPM
+10.2k Golang : Identifying Golang HTTP client request
+9.5k Golang : Play .WAV file from command line
+17.6k Golang : Linked list example
+20.9k Android Studio : AlertDialog and EditText to get user string input example