1. Custom DNS resolver for the default HTTP client in Go
The default HTTP client in Go uses the default DNS resolver available on the machine. There are some cases where you might want to use a different DNS resolver.
I want to quickly show how you can change the DNS resolver for the default HTTP client. We are using this same method for our custom DNS resolver in my company: Violetnorth
// Changing DNS resolver
package main
import (
"context"
"io/ioutil"
"log"
"net"
"net/http"
"time"
)
func main() {
var (
dnsResolverIP = "8.8.8.8:53" // Google DNS resolver.
dnsResolverProto = "udp" // Protocol to use for the DNS resolver
dnsResolverTimeoutMs = 5000 // Timeout (ms) for the DNS resolver (optional)
)
dialer := &net.Dialer{
Resolver: &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
d := net.Dialer{
Timeout: time.Duration(dnsResolverTimeoutMs) * time.Millisecond,
}
return d.DialContext(ctx, dnsResolverProto, dnsResolverIP)
},
},
}
dialContext := func(ctx context.Context, network, addr string) (net.Conn, error) {
return dialer.DialContext(ctx, network, addr)
}
http.DefaultTransport.(*http.Transport).DialContext = dialContext
httpClient := &http.Client{}
// Testing the new HTTP client with the custom DNS resolver.
resp, err := httpClient.Get("https://www.violetnorth.com")
if err != nil {
log.Fatalln(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
log.Println(string(body))
}
It only takes a few lines but you have to overwrite the Dial function in the Resolver which is inside the Dialer which is inside the Transport function.
It might seem weird but it actually makes a lot of sense, follow the functions from top to bottom, DefaultTransport -> DialContext -> Dialer -> Resolver -> Dial
We are changing the Dial function which dials the DNS server to resolve the request, so it should be inside the Resolver. But this whole thing is in the DialContext of the actual HTTP request.
You have to dial the DNS resolver first, resolve the IP, then dial that resolved IP to make the HTTP request.
Anyways that’s pretty much it. Changing the DNS resolver in the default HTTP client.
本文介绍了如何在Go语言的默认HTTP客户端中替换DNS解析器,通过创建自定义的DNS解析器实例并覆盖`net/http`包中的`DialContext`方法来实现。作者分享了Violetnorth公司的实践案例,展示了如何仅需几行代码即可定制DNS查询过程。
2811

被折叠的 条评论
为什么被折叠?



