Created
December 5, 2019 19:23
-
-
Save xkortex/131572573628e0f4a29fb5ab8bb009e0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import ( | |
"fmt" | |
"golang.org/x/net/context" | |
"net" | |
"time" | |
) | |
type AddrResponse struct { | |
addrs []string | |
err error | |
} | |
func TimeoutLookupHost(host string) (addrs []string, err error) { | |
timeout_ns := 0.1 * 1e9 | |
timeout := time.Duration(int(timeout_ns)) | |
ctx, cancel := context.WithTimeout(context.Background(), timeout) | |
defer cancel() | |
ch := make(chan AddrResponse, 1) | |
defer close(ch) | |
go func() { | |
select { | |
default: | |
addrs, err := net.LookupHost(host) | |
ch <- AddrResponse{addrs: addrs, err: err} | |
case <-ctx.Done(): | |
fmt.Println("Exiting gofunc") | |
return | |
} | |
}() | |
select { | |
case out:= <-ch: | |
fmt.Println("Read from ch: ", out) | |
case <-ctx.Done(): | |
fmt.Println("Timed out from context") | |
} | |
fmt.Println("Exiting TimeoutFunc") | |
return nil, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment