我正在尝试使N个获得请求,但是我的代码可用于8个URL,但10个始终可以堆叠而没有问题。
我是GO新手,所以我不明白这个问题。
我正在尝试编写一个应用程序以击败具有相同任务的.NET应用程序。
您能建议出什么问题吗?
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
//"bufio"
"time"
)
type HttpResponse struct {
url string
response *http.Response
err error
}
func main() {
fmt.Println("Hello, world3.")
var urls []string = []string{
"www.webmagnat.ro",
"nickelfreesolutions.com",
"scheepvaarttelefoongids.nl",
"tursan.net",
"plannersanonymous.com",
"saltstack.com",
"deconsquad.com",
"migom.com",
"tjprc.org",
"worklife.dk",
"food-hub.org"}
start := time.Now()
results := asyncHttpGets(urls)
f, err := os.Create("test.txt")
if err != nil {
fmt.Println(err)
return
}
for _, result := range results {
fmt.Printf("%s status: %s\n", result.url,
result.response.Status)
l, err := f.WriteString(result.url+"\n")
if err != nil {
fmt.Println(err)
f.Close()
return
}
_ = l
}
t := time.Now()
elapsed := t.Sub(start)
fmt.Printf("Ellipsed: %s\n", elapsed)
err = f.Close()
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Buy, world2.")
}
func asyncHttpGets(urls []string) []*HttpResponse {
ch := make(chan *HttpResponse, len(urls)) // buffered
responses := []*HttpResponse{}
for _, url := range urls {
go func(url string) {
fmt.Printf("Fetching %s \n", url)
resp, err := http.Get("http://" + url)
if err != nil {
fmt.Printf("Failed to fetch %s\n", err)
return
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
fmt.Printf("HTTP Response Status : %v", resp.StatusCode)
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
bodyString := string(bodyBytes)
fmt.Printf("HTTP Response Content Length : %v\n", len(bodyString))
}
ch <- &HttpResponse{url, resp, err}
}(url)
}
for {
select {
case r := <-ch:
fmt.Printf("%s was fetched\n", r.url)
responses = append(responses, r)
if len(responses) == len(urls) {
return responses
}
case <-time.After(50 * time.Millisecond):
fmt.Printf(".")
}
}
return responses
}
我正在尝试使N个获得请求,但是我的代码可用于8个URL,但10个始终可以毫无问题地堆叠。我是GO的新手,所以我不明白这个问题。我正在尝试编写一个应用程序以... ...>
这里的第一个问题是在发生错误的情况下您不会返回响应,因此len(responses) == len(urls)
可能永远不会匹配,从而迫使循环永远继续。
首先为并发请求添加sync.WaitGroup
您必须添加Wait Group构造,因为当两个线程执行时,主线程结束。参见:https://yourbasic.org/golang/wait-for-goroutines-waitgroup/
您可以使用以下库: