Skip to content

chillum/dnscache

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

18 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

DNS Lookup Cache

godoc license

The dnscache package provides a DNS cache layer to Go's net.Resolver.

Install

Install using the "go get" command:

go get github.com/chillum/dnscache

Usage

Create a new instance and use it in place of net.Resolver. New names will be cached. Call the Refresh method at regular interval to update cached entries and cleanup unused ones.

resolver := &dnscache.Resolver{}

// First call will cache the result
addrs, err := resolver.LookupHost(context.Background(), "example.com")

// Subsequent calls will use the cached result
addrs, err = resolver.LookupHost(context.Background(), "example.com")

// Call to refresh will refresh names in cache. If you pass true, it will also
// remove cached names not looked up since the last call to Refresh. It is a good idea
// to call this method on a regular interval.
go func() {
    clearUnused := true
    t := time.NewTicker(5 * time.Minute)
    defer t.Stop()
    for range t.C {
        resolver.Refresh(clearUnused)
    }
}()

If you are using an http.Transport, you can use this cache by specifying a DialContext function:

r := &dnscache.Resolver{}
t := &http.Transport{DialContext: r.Dial}

Please note that for now the Dial function is rather minimalistic and there are some restrictions. Consult godoc for limitations. If you need extra functionality, but don't want to modify the library, you can specify it inline like:

r := &dnscache.Resolver{}
t := &http.Transport{
    DialContext: func(ctx context.Context, network string, addr string) (conn net.Conn, err error) {
        separator := strings.LastIndex(addr, ":")
        ips, err := r.LookupHost(ctx, addr[:separator])
        if err != nil {
            return nil, err
        }
        for _, ip := range ips {
            conn, err = net.Dial(network, ip+addr[separator:])
            if err == nil {
                break
            }
        }
        return
    },
}

Languages

  • Go 100.0%