我正在尝试发出 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
}
https://play.golang.org/p/pcKYYM_PgIX
慕尼黑5688855
UYOU
MYYA
相关分类