英文:
First HTTP request always slow
问题
我有以下代码:
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
英文:
I have following code
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)
}
The time of resp, _ := Get(url1, cl, header)
is always slow
Regardless of url1
change to https://example2.com or https://www.google.com/
like this
1 254.156959ms
2 34.183151ms
2 87.880252ms
答案1
得分: 2
这是一篇关于解决Go的DNS问题的精彩文章,你可以在这里找到它。文章简要提到了net
包文档中的Name_Resolution部分。
如果你喜欢阅读代码(和注释),你可以在src/net/lookup.go
中找到更多信息。
简而言之,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
英文:
There is a beautiful article on medium on resolving go's DNS issues. Shortly it refers to the Name_Resolution of the net
package documentation.
More info can be found in src/net/lookup.go
, if you like to read code (and comments).
TL/DR: go can use different dns resolvers, wich you can enable/or test with
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论