44 lines
683 B
Go
Raw Normal View History

2017-06-23 13:38:46 +00:00
package middleware
import (
"net"
"time"
cache "github.com/patrickmn/go-cache"
)
var ipToHosts = cache.New(60*time.Minute, 30*time.Minute)
// GetHostsForIP returns all host names for the given IP (if cached).
func GetHostsForIP(ip string) []string {
hosts, found := ipToHosts.Get(ip)
2017-06-23 13:51:26 +00:00
if !found {
hosts = findHostsForIP(ip)
}
if hosts == nil {
2017-06-23 13:38:46 +00:00
return nil
}
return hosts.([]string)
}
// Finds all host names for the given IP
2017-06-23 13:51:26 +00:00
func findHostsForIP(ip string) []string {
2017-06-23 13:38:46 +00:00
hosts, err := net.LookupAddr(ip)
if err != nil {
2017-06-23 13:51:26 +00:00
return nil
2017-06-23 13:38:46 +00:00
}
if len(hosts) == 0 {
2017-06-23 13:51:26 +00:00
return nil
2017-06-23 13:38:46 +00:00
}
// Cache host names
ipToHosts.Set(ip, hosts, cache.DefaultExpiration)
2017-06-23 13:51:26 +00:00
return hosts
2017-06-23 13:38:46 +00:00
}