Skip to content

Instantly share code, notes, and snippets.

@rafaeljesus
Created November 11, 2016 23:13
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rafaeljesus/e15b3ac024bfc2e8b04a0ae32fced1a1 to your computer and use it in GitHub Desktop.
Save rafaeljesus/e15b3ac024bfc2e8b04a0ae32fced1a1 to your computer and use it in GitHub Desktop.
Asynchronous http request in golang
type HttpResp struct {
Id string
Resp *http.Response
Err error
}
func AsyncGet(urls map[string]string) []*HttpResp {
ch := make(chan *HttpResp)
responses := []*HttpResp{}
for track_id, url := range urls {
go func(i, u string) {
resp, err := http.Get(u)
ch <- &HttpResp{i, resp, err}
}(track_id, url)
}
loop:
for {
select {
case r := <-ch:
responses = append(responses, r)
if len(responses) == len(urls) {
break loop
}
case <-time.After(50 * time.Millisecond):
fmt.Printf(".")
}
}
return responses
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment