Created
May 31, 2019 12:05
-
-
Save guimeisang/da4737696ab40a5a294c3648ef1dc679 to your computer and use it in GitHub Desktop.
可以异步的请求http列表
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"net/http" | |
"time" | |
) | |
var urls = []string{ | |
"http://pulsoconf.co/", | |
"http://golang.org/", | |
"http://matt.aimonetti.net/", | |
} | |
type HttpResponse struct { | |
url string | |
response *http.Response | |
err error | |
} | |
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(url) | |
resp.Body.Close() | |
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 | |
} | |
func main() { | |
results := asyncHttpGets(urls) | |
for _, result := range results { | |
fmt.Printf("%s status: %s\n", result.url, | |
result.response.Status) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment