Skip to content

vicanso/dnscache

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

44 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

DNS Cache

Build Status

DNS Cache for http client

API

New

create a dns cache instance

  • ttl cache's ttl seconds
onStats := func(h string, d time.Duration, _ []string) {
  fmt.Println(d)
}
dc := dnscache.New(
  time.Minute,
  dnscache.PolicyOption(dnscache.PolicyRandom),
  dnscache.StaleOption(time.Minute),
  dnscache.OnStatsOption(onStats),
  dnscache.NetworkOption(dnscache.NetworkIPV4),
)

Lookup

lookup ip address for host

  • host host name
dc := dnscache.New(time.Minute)
ipAddrs, err := dc.Lookup(context.Background(), "www.baidu.com")

LookupWithCache

lookup ip address for host, it will use the cache first.

  • host host name
dc := dnscache.New(time.Minute)
ipAddrs, err := dc.LookupWithCache(context.Background(), "www.baidu.com")

GetDialContext

get dial context function for http client

dc := dnscache.New(time.Minute)
http.DefaultClient.Transport = &http.Transport{
  DialContext: dc.GetDialContext(),
}
resp, err := http.Get("https://www.baidu.com/")

Set

set the dns cache, if the CreatedAt is less than 0, it will never be expired.

dc := dnscache.New(time.Minute)
dc.Set("www.baidu.com", IPCache{
  CreatedAt: time.Now().Unix(),
  IPAddrs: []net.IP{
    net.ParseIP("1.1.1.1"),
  },
})

Get

get the dns cache

dc := dnscache.New(time.Minute)
host := "www.baidu.com"
dc.Set(host, IPCache{
  CreatedAt: time.Now().Unix(),
  IPAddrs: []net.IP{
    net.ParseIP("1.1.1.1"),
  },
})
cache, ok := dc.Get(host)