Last active
August 29, 2015 14:14
-
-
Save kevin-cantwell/5d7787d8394a678f3a9c to your computer and use it in GitHub Desktop.
This file contains 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" | |
"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