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
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s