Add support for custom DNS resolvers

This commit is contained in:
9seconds
2026-02-27 16:08:28 +01:00
parent 1151291535
commit 317d7380cb
4 changed files with 124 additions and 0 deletions
+53
View File
@@ -0,0 +1,53 @@
package network
import (
"context"
"fmt"
"net"
"net/url"
"time"
"github.com/ncruces/go-dns"
)
var dnsCacheOptions = []dns.CacheOption{
dns.MaxCacheEntries(dns.DefaultMaxCacheEntries),
dns.MaxCacheTTL(time.Hour),
dns.NegativeCache(false),
}
func GetDNS(u *url.URL) (*net.Resolver, error) {
if u == nil {
return dns.NewCachingResolver(nil, dnsCacheOptions...), nil
}
switch u.Scheme {
case "tls":
return dns.NewDoTResolver(u.Host, dns.DoTCache(dnsCacheOptions...))
case "https":
if u.Path == "" {
u.Path = "/dns-query"
}
return dns.NewDoHResolver(u.String(), dns.DoHCache(dnsCacheOptions...))
case "udp", "":
default:
return nil, fmt.Errorf("unsupported DNS %v", u)
}
port := u.Port()
if port == "" {
port = "53"
}
hostport := net.JoinHostPort(u.Hostname(), port)
dialer := &net.Dialer{}
resolver := &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
return dialer.DialContext(ctx, "udp", hostport)
},
}
return dns.NewCachingResolver(resolver, dnsCacheOptions...), nil
}