49 lines
798 B
Go
Raw Normal View History

2017-06-23 13:38:46 +00:00
package middleware
import (
"net"
2018-07-07 04:23:00 +00:00
"sync"
2017-06-23 13:38:46 +00:00
"time"
cache "github.com/patrickmn/go-cache"
)
var ipToHosts = cache.New(60*time.Minute, 30*time.Minute)
2018-07-07 04:23:00 +00:00
var ipToHostsMutex sync.Mutex
2017-06-23 13:38:46 +00:00
// GetHostsForIP returns all host names for the given IP (if cached).
2018-07-07 04:17:30 +00:00
func GetHostsForIP(ip string) ([]string, bool) {
2018-07-07 04:23:00 +00:00
ipToHostsMutex.Lock()
defer ipToHostsMutex.Unlock()
2017-06-23 13:38:46 +00:00
hosts, found := ipToHosts.Get(ip)
2017-06-23 13:51:26 +00:00
if !found {
hosts = findHostsForIP(ip)
}
if hosts == nil {
2018-07-07 04:17:30 +00:00
return nil, found
2017-06-23 13:38:46 +00:00
}
2018-07-07 04:17:30 +00:00
return hosts.([]string), found
2017-06-23 13:38:46 +00:00
}
// 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
}