Created
November 11, 2016 23:13
-
-
Save rafaeljesus/e15b3ac024bfc2e8b04a0ae32fced1a1 to your computer and use it in GitHub Desktop.
Asynchronous http request in golang
This file contains hidden or 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
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