Created
October 25, 2016 18:35
-
-
Save vmanyushin/7025e92f9a16999e9160c44a5ebc702a to your computer and use it in GitHub Desktop.
golang net.LookupHost wrapper for timeout's
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"net" | |
"time" | |
"fmt" | |
"errors" | |
) | |
func main() { | |
ipaddr, err := LookupHost("rambler.ru", time.Millisecond * 200) | |
fmt.Printf("domain: %s, ipaddr: %v, error: %s\n", "rambler.ru", ipaddr, err) | |
ipaddr, err = LookupHost("0-0-0.ru", time.Millisecond * 200) | |
fmt.Printf("domain: %s, ipaddr: %v, error: %s\n", "rambler.ru", ipaddr, err) | |
} | |
func LookupHost(hostname string, timeout time.Duration) ([]string, error) { | |
c1 := make(chan []string) | |
c2 := make(chan error) | |
var ipaddr []string | |
var err error | |
go func() { | |
var ipaddr []string | |
ipaddr, err := net.LookupHost(hostname) | |
if err != nil { | |
c2 <- err | |
} | |
c1 <- ipaddr | |
}() | |
select { | |
case ipaddr = <-c1: | |
case err = <-c2: | |
case <-time.After(timeout): | |
return ipaddr, errors.New("timeout") | |
} | |
if err != nil { | |
return ipaddr, errors.New("timeout") | |
} | |
return ipaddr, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output
0-0-0.ru resolve over 3sec, but limit is 0.2s