Artem Piskun
Posted on September 30, 2018
There are some points where you need TTL to do something, i.e. API Request or some other restrictions. In golang you could do it in very simple way using goroutines and standart time package.
The basics to solve the task are looked something like this.
// First of all you need a channel to interract with the request
c := make(chan int, 1)
// start anonymous routine with the some function call
go func() {
result := someFunc()
c <- result
close(c)
}()
// start timer
timer := time.NewTimer(<timeout>)
defer timer.Stop()
var result int
var err error
select {
case result = <-c:
// do nothing, break select
case <-timer.C:
err = fmt.Errorf("time exceeded")
}
// handle error and use the result in the code
And as an example there is a net.LookupIP fuction call from the standart package with a TTL
func main() {
ips, err := lookupIPs("https://dev.to", time.Second)
if err != nil {
// check the error
}
// do something with the list of ips
}
type lookupIP struct {
ips []net.IP
err error
}
func lookupIPs(url string, timeout time.Duration) ([]net.IP, error) {
c := make(chan lookupIP, 1)
go func() {
ips, err := net.LookupIP(url)
c <- lookupIP{ips, err}
close(c)
}()
timer := time.NewTimer(timeout)
defer timer.Stop()
var lIP lookupIP
select {
case lIP = <-c:
// do nothing, break select
case <-timer.C:
lIP.err = fmt.Errorf("lookup ip: time exceeded")
}
if lIP.err != nil {
return nil, lIP.err
}
return lIP.ips, nil
}
💖 💪 🙅 🚩
Artem Piskun
Posted on September 30, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.