Skip to content

Instantly share code, notes, and snippets.

@kevin-cantwell
Last active August 29, 2015 14:14
Show Gist options
  • Save kevin-cantwell/5d7787d8394a678f3a9c to your computer and use it in GitHub Desktop.
Save kevin-cantwell/5d7787d8394a678f3a9c to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"net/http"
"io/ioutil"
)
const workers int 3
func main() {
url := "http://example.com"
resp, err := fetch(url)
if err != nil {
panic(err)
}
defer resp.Body.Close()
bytes, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(bytes))
}
type Result struct {
Resp *http.Response
Err error
}
func fetchUrl(url string, resultChan <-chan) {
resp, err := http.Get(url)
resultChan <- Result{resp, err}
}
func fetch(url string) (*http.Response, error) {
resultChan := make(chan Result, 1)
for i := 0; i < workers; i++) {
go fetchUrl(url, resultChan)
}
for i := 0; i < workers; i++) {
result <- resultChan
if i = workers-1 {
return nil, result.Err
} else if result.Resp == nil {
continue
} else {
return result.Resp, nil
}
}
return nil, errors.New("no result")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment