/
client.go
60 lines (52 loc) · 1.86 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package sources
import (
"context"
"net"
"net/http"
"strings"
"time"
"github.com/hashicorp/go-cleanhttp"
"github.com/shoenig/donutdns/agent"
)
// client creates an http.Client with an explicit DNS server. This is necessary
// sometimes, like when deploying donutdns on Nomad or Kubernetes where IP tables
// will have 0.0.0.0:53 redirected to this agent, which in turn needs to bootstrap
// itself with the origin sources before it can serve requests.
//
// It might be possible to eliminate this chicken-egg problem using the healthcheck
// plugin or something similar, where we just fallthrough past the donutdns plugin
// until it's actually ready. A project for a rainy day.
//
// Totally ripped from https://koraygocmen.medium.com/custom-dns-resolver-for-the-default-http-client-in-go-a1420db38a5d
func client(fwd *agent.Forward) *http.Client {
var (
dnsResolverIP = "1.1.1.1:53" // Cloudflare DNS resolver.
dnsResolverProto = "udp" // Protocol to use for the DNS resolver
dnsResolverTimeoutMs = 5000 // Timeout (ms) for the DNS resolver (optional)
)
// use the DONUT_DNS_UPSTREAM_1 value if set, setting default port if necessary
if len(fwd.Addresses) > 0 {
dnsResolverIP = fwd.Addresses[0]
if !strings.Contains(dnsResolverIP, ":") {
dnsResolverIP += ":53"
}
}
dialer := &net.Dialer{
Resolver: &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
return (&net.Dialer{
Timeout: time.Duration(dnsResolverTimeoutMs) * time.Millisecond,
}).DialContext(ctx, dnsResolverProto, dnsResolverIP)
},
},
}
dialContext := func(ctx context.Context, network, addr string) (net.Conn, error) {
return dialer.DialContext(ctx, network, addr)
}
tr := cleanhttp.DefaultTransport()
tr.DialContext = dialContext
c := cleanhttp.DefaultClient()
c.Transport = tr
return c
}