Created
February 12, 2016 15:12
-
-
Save andrefsp/68d0bfd792893dbc3aa7 to your computer and use it in GitHub Desktop.
Parallel url fetcher written in go
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 ( | |
"encoding/json" | |
"fmt" | |
"log" | |
"net/http" | |
) | |
func fetch_url(url string, responses *chan string) { | |
log.Println("Fetching ", url) | |
response, err := http.Get(url) | |
log.Println("Finish fetching ", url, response.Status) | |
if err != nil { | |
*responses <- "Failed" | |
} else { | |
*responses <- response.Status | |
} | |
} | |
func handler(w http.ResponseWriter, r *http.Request) { | |
urls := []string{ | |
"https://google.com", | |
"https://www.facebook.com", | |
"https://www.ebay.co.uk", | |
} | |
// trigger requests | |
responses := make(chan string, len(urls)) | |
for _, url := range urls { | |
go fetch_url(url, &responses) | |
} | |
// collect responses | |
statuses := make([]string, len(urls)) | |
for i := 0; i < len(statuses); i++ { | |
statuses[i] = <-responses | |
} | |
close(responses) | |
responseText, _ := json.Marshal(statuses) | |
fmt.Fprintf(w, string(responseText)) | |
} | |
func main() { | |
http.HandleFunc("/", handler) | |
http.ListenAndServe(":8000", nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment