DNS Lookup with Timeout

Resolve a hostname through the default resolver with a context deadline, sort the addresses, and surface lookup failures clearly.

GoData Fetching

Code

snippet
package main

import (
	"context"
	"fmt"
	"net"
	"sort"
	"time"
)

func Lookup(ctx context.Context, host string) ([]string, error) {
	addresses, err := net.DefaultResolver.LookupHost(ctx, host)
	if err != nil {
		return nil, err
	}
	sort.Strings(addresses)
	return addresses, nil
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()
	addresses, err := Lookup(ctx, "localhost")
	if err != nil {
		fmt.Println("lookup failed:", err)
		return
	}
	for _, address := range addresses {
		fmt.Println(address)
	}
}