我完成了建议的游览,在 YouTube 上观看了一些教程和 gopher 会议。差不多就是这样。
我有一个项目需要我发送获取请求并将结果存储在文件中。但 URL 的数量约为 8000 万。
我只测试 1000 个 URL。
问题:尽管我遵循了一些指导方针,但我认为我无法使其并发。我不知道怎么了。但也许我错了,它是并发的,对我来说似乎并不快,速度感觉就像顺序请求。
这是我写的代码:
package main
import (
"bufio"
"io/ioutil"
"log"
"net/http"
"os"
"sync"
"time"
)
var wg sync.WaitGroup // synchronization to wait for all the goroutines
func crawler(urlChannel <-chan string) {
defer wg.Done()
client := &http.Client{Timeout: 10 * time.Second} // single client is sufficient for multiple requests
for urlItem := range urlChannel {
req1, _ := http.NewRequest("GET", "http://"+urlItem, nil) // generating the request
req1.Header.Add("User-agent", "Mozilla/5.0 (X11; Linux i586; rv:31.0) Gecko/20100101 Firefox/74.0") // changing user-agent
resp1, respErr1 := client.Do(req1) // sending the prepared request and getting the response
if respErr1 != nil {
continue
}
defer resp1.Body.Close()
if resp1.StatusCode/100 == 2 { // means server responded with 2xx code
text1, readErr1 := ioutil.ReadAll(resp1.Body) // try to read the sourcecode of the website
if readErr1 != nil {
log.Fatal(readErr1)
}
f1, fileErr1 := os.Create("200/" + urlItem + ".txt") // creating the relative file
if fileErr1 != nil {
log.Fatal(fileErr1)
}
defer f1.Close()
_, writeErr1 := f1.Write(text1) // writing the sourcecode into our file
if writeErr1 != nil {
log.Fatal(writeErr1)
}
}
}
}
我的问题是:为什么这段代码不能同时工作?我该如何解决我上面提到的问题。发出并发 GET 请求时我做错了什么吗?
湖上湖
慕少森
相关分类