可能这个问题比较小白,大家轻喷。
我用 Golang 中http库的Get函数写个简单的下载网页的工具,发现下载网页时间很长,比 curl 长很多:

Golang 代码:
// Fetch prints the content found at a URL.
package main
import (
"time"
"fmt"
"io"
"net/http"
"os"
"strings"
)
func main() {
for _, url := range os.Args[1:] {
start := time.Now()
if !(strings.HasPrefix(url, "https://") || strings.HasPrefix(url, "http://")) {
url = "http://" + url
}
resp, err := http.Get(url)
if err != nil {
fmt.Fprintf(os.Stderr, "fetch: %v\n", err)
os.Exit(1)
}
fmt.Printf("[\033[0;31m%d\033[0m] %v\n", resp.StatusCode, resp.Request.URL)
// Test download cost.
//fmt.Println("Download cost:", time.Since(start))
if _, err := io.Copy(os.Stdout, resp.Body); err != nil {
fmt.Fprintf(os.Stderr, "\033[0;31mERROR\033[0m %v\n", err)
os.Exit(1)
}
fmt.Println("Total cost:", time.Since(start))
}
}
看到这么大的差距,我以为是io.Copy可能出了点问题,就在io.Copy前添了一个时间测试,结果:
Download cost: 21.651425s
Total cost: 21.656501s
可以看到时间主要是花在http.Get这里了。
我多次测试后都可以复现(包含测试不同网站),Google 也没有什么结果,搜索关键词都不知道怎么设置。。
这究竟是啥原因啊?