Skip to content

Instantly share code, notes, and snippets.

@ripiuk
Created December 15, 2020 07:44
Show Gist options
  • Save ripiuk/8b3076226f5104e96e2ad42a521acf5b to your computer and use it in GitHub Desktop.
Save ripiuk/8b3076226f5104e96e2ad42a521acf5b to your computer and use it in GitHub Desktop.
Fetch several web pages simultaneously, and print the URL of the biggest page (defined as the most bytes in the response)
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
type Page struct {
URL string
Size int
}
var urls = [...]string{
"https://www.google.com/",
"https://www.youtube.com/",
"https://www.songsterr.com/",
"https://open.spotify.com/",
}
func main() {
res := make(chan Page)
for _, url := range urls {
go func(url string) {
resp, err := http.Get(url)
if err != nil {
panic(err)
}
defer resp.Body.Close()
bs, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
res <- Page{
URL: url,
Size: len(bs),
}
}(url)
}
var biggest Page
for range urls {
currPage := <-res
if currPage.Size > biggest.Size {
biggest = currPage
}
}
fmt.Println("The biggest page:", biggest.URL)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment