diff options
author | Jonathan Turner <jt@jtnet.co.uk> | 2017-11-30 11:22:44 -0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2017-11-30 11:22:44 -0800 |
commit | 7c21cc9329507ae42a2a5102de2165768fb40404 (patch) | |
tree | 14a902a1bb0c20caa48e385807b2b6bfc5680668 | |
parent | 4ea2527295b59bc173164ce14bdd23e374c2e9d9 (diff) | |
parent | aa8e2ae41f043d4a55e640659e16d784db6fd150 (diff) |
Merge pull request #1 from jcmturner/ons
support for overriding OS level name server (Go >=1.9)
-rw-r--r-- | srv.go | 31 |
1 files changed, 30 insertions, 1 deletions
@@ -1,8 +1,11 @@ package dnsutils import ( + "context" + "fmt" "math/rand" "net" + "os" "sort" ) @@ -18,8 +21,19 @@ import ( // // Do something such as dial this SRV. If fails move on the the next or break if it succeeds. // i += 1 // } +// +// To override the operating system's name server set the DNSUTILS_OVERRIDE_NS environment variable. +// The override should also include the port. For example 127.0.0.1:53 func OrderedSRV(service, proto, name string) (int, map[int]*net.SRV, error) { - _, addrs, err := net.LookupSRV(service, proto, name) + var addrs []*net.SRV + var err error + ns := os.Getenv("DNSUTILS_OVERRIDE_NS") + if ns != "" { + res := net.Resolver{Dial: overrideNS} + _, addrs, err = res.LookupSRV(context.Background(), service, proto, name) + } else { + _, addrs, err = net.LookupSRV(service, proto, name) + } if err != nil { return 0, make(map[int]*net.SRV), err } @@ -27,6 +41,21 @@ func OrderedSRV(service, proto, name string) (int, map[int]*net.SRV, error) { return index, osrv, nil } +func overrideNS(ctx context.Context, network, address string) (conn net.Conn, err error) { + // Ignore the address provided and override with an environment variable if it is defined + ns := os.Getenv("DNSUTILS_OVERRIDE_NS") + if ns != "" { + address = ns + } + if network == "tcp" || network == "udp" { + var d net.Dialer + conn, err = d.DialContext(ctx, network, address) + return + } + err = fmt.Errorf("unsupported network protocol %s for DNS lookup", network) + return +} + func orderSRV(addrs []*net.SRV) (int, map[int]*net.SRV) { // Initialise the ordered map var o int |