Skip to content

Instantly share code, notes, and snippets.

@xkortex
Created December 5, 2019 19:23
Show Gist options
  • Save xkortex/131572573628e0f4a29fb5ab8bb009e0 to your computer and use it in GitHub Desktop.
Save xkortex/131572573628e0f4a29fb5ab8bb009e0 to your computer and use it in GitHub Desktop.
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