Home > Back-end >  Is golang caching DNS?
Is golang caching DNS?

Time:12-25

I'm running a piece of golang code to resolve a url.

This url should returns one ip on 50% of the requests and another ip on the others 50%.

This is working when I perform the host command but not when I resolve the DNS using Go. On my research, every answer I saw they said Golang doesn't cache DNS but the behavior seems to be different.

Can anyone clarify that?

Here is my code and I'm using a for loop to run it 100 times:

for value in {1..100};do go run main.go;done

    "fmt"
    "net"
)

func main() {
    iprecords, _ := net.LookupIP("google.com")
    for _, ip := range iprecords {
        fmt.Println(ip)
    }
}

CodePudding user response:

When using CGO_ENABLED=1 (the go build default) on OS X, according to the net package docs, Go will use:

... the cgo-based resolver ... on systems that do not let programs make direct DNS requests (OS X)

so if you are observing DNS caching on MacOS - then this is happening at OS-level.

You can try using the Go's native DNS resolver to see if that is a viable alternative.

You co this this by either:

CGO_ENABLED=0 go build  # disabling CGO

or more subtly using the runtime env var:

export GODEBUG=netdns=go    # force pure Go resolver

This has its limitations, for example on VPN split-tunnel DNS routing will not work using Go's native resolver. YMMV.

  • Related