我有以下代码
package main
import (
"fmt"
"net/http"
"time"
)
func Get(url string, client *http.Client, header []string) (*http.Response, error) {
start := time.Now()
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
for i := 0; i < len(header)/2; i++ {
req.Header.Add(header[2*i], header[2*i+1])
}
resp, err := client.Do(req)
fmt.Println(time.Until(start))
return resp, nil
}
func main() {
header := []string{"accept-encoding", "gzip, deflate, br"}
cl := &http.Client{}
url1 := "https://example1.com"
url2 := "https://example2.com"
url3 := "https://www.google.com/"
resp, _ := Get(url1, cl, header)
resp, _ = Get(url2, cl, header)
resp, _ = Get(url3, cl, header)
fmt.Println(resp)
}
resp, _ := Get(url1, cl, header)
的时间总是很慢
无论 url1
更改为 https://example2.com或https://www.google.com/
像这样
1 254.156959ms
2 34.183151ms
2 87.880252ms
最佳答案
有一个美丽的article中等关于解决 go 的 DNS 问题。简而言之,它指的是Name_Resolution net
包文档。
如果您想阅读code,可以在src/net/lookup.go
中找到更多信息。 (和评论)。
TL/DR:go 可以使用不同的 dns 解析器,您可以启用/或测试
GODEBUG=netdns=1 go run main.go
> go package net: hostLookupOrder(redis) = cgo
// osx/macosx case
GODEBUG=netdns=go+2 go run main.go
> go package net: GODEBUG setting forcing use of Go’s resolver go
> package net: hostLookupOrder(redis) = files,dns
关于go - 第一个 HTTP 请求总是很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68647626/