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

gosnippet
32 lines
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)
	}
}

How the snippet works

Under the hood: the functions Lookup and main.

A single loop drives the file — for _, address := range addresses. The Go idiom runs throughout — 2 if err != nil checks, each handling the failure on the spot. A defer statement pins the cleanup to the function boundary rather than scattering it through the body.

Points of care

  • The package manager never enters the picture for this snippet.
  • The function reports failure by returning error — callers branch on it before touching other results.

Applying it

The main signature appears as func Lookup(ctx context.Context, host string) ([]string, error)

Output lines are prefixed (lookup failed:), so every step’s effect stays easy to trace.

Start the program and main runs Lookup one after another.

Statements that decide the outcome

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
}
for _, address := range addresses {
fmt.Println(address)
}
if err != nil {
fmt.Println("lookup failed:", err)
return
}

Interactive Tools for This Topic

FAQ

What is the error handling style?
As returned `error` values, checked at 2 sites — callers must branch on `err` before using the other return values. No panics or exceptions in the snippet.
What does DNS Lookup with Timeout print when run?
The script runs standalone; its 1 labeled outputs include `lookup failed:`.