Created
July 15, 2016 12:26
-
-
Save sumitramteke/87460575614b82d411386c2388d04e34 to your computer and use it in GitHub Desktop.
Asynchronous HTTP response handling
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
package main | |
import ( | |
"fmt" | |
"net/http" | |
"time" | |
) | |
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) | |
fmt.Println(" \nHTTPRequest from : ", track_id) | |
ch <- &HttpResp{i, resp, err} | |
}(track_id, url) | |
} | |
loop: | |
for { | |
select { | |
case r := <-ch: | |
fmt.Println("HTTPResponed : ", r.Id) | |
responses = append(responses, r) | |
if len(responses) == len(urls) { | |
break loop | |
} | |
case <-time.After(50 * time.Millisecond): | |
fmt.Printf(".") | |
} | |
} | |
return responses | |
} | |
func main() { | |
urls := map[string]string{ | |
"google": "http://www.google.co.in", | |
"duckduckgo": "https://duckduckgo.com", | |
"yahoo": "https://in.yahoo.com/?p=us", | |
} | |
AsyncGet(urls) | |
//time.Sleep(100 * time.Millisecond) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment