在我的GO应用程序中,我经常需要查询列表或URL。由于GO从头开始是异步的,因此它是使用此功能的理想场所。

解决该问题的最佳方法是什么?我发现了blog提出解决方案,但是它失败,并显示一个空的URL列表。

谢谢!

最佳答案

我已经对您提供的博客链接中的代码进行了调整,使其对错误的适应性更强。

下面的代码应进行编译,并应处理边界情况,例如空的urls输入片。

package main

import (
    "fmt"
    "net/http"
    "os"
    "time"
)

const timeout time.Duration = 3 * time.Second

var urls = []string{
    "http://golang.org/",
    "http://stackoverflow.com/",
    "http://i.wanta.pony/", // Should error
}

type httpResponse struct {
    url      string
    response *http.Response
    err      error
}

func asyncHTTPGets(urls []string, ch chan *httpResponse) {
    for _, url := range urls {
        go func(url string) {
            resp, err := http.Get(url)
            ch <- &httpResponse{url, resp, err}
        }(url)
    }
}

func main() {
    responseCount := 0
    ch := make(chan *httpResponse)
    go asyncHTTPGets(urls, ch)
    for responseCount != len(urls) {
        select {
        case r := <-ch:
            if r.err != nil {
                fmt.Printf("Error %s fetching %s\n", r.err, r.url)
            } else {
                fmt.Printf("%s was fetched\n", r.url)
            }
            responseCount++
        case <-time.After(timeout):
            os.Exit(1)
        }
    }
}

Playground

09-10 07:34
查看更多