Created
February 14, 2019 23:57
-
-
Save Deleplace/dcbd1c7db7bff3dcbaf3a0fe08dd256b to your computer and use it in GitHub Desktop.
A Google Cloud Function that fetches 10 remote resources concurrently
This file contains hidden or 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 p | |
import ( | |
"fmt" | |
"io/ioutil" | |
"log" | |
"math/rand" | |
"net/http" | |
"sync" | |
"time" | |
) | |
func Concurrent(w http.ResponseWriter, r *http.Request) { | |
titles := []string{ | |
"New_York_City", | |
"San_Francisco", | |
"Miami", | |
"Los_Angeles", | |
"Moscow", | |
"Tokyo", | |
"London", | |
"Berlin", | |
"Sao_Paulo", | |
"Lagos", | |
} | |
t := time.Now() | |
var wg sync.WaitGroup | |
wg.Add(len(titles)) | |
for _, title := range titles { | |
title := title | |
go func() { | |
fetch(title) | |
wg.Done() | |
}() | |
} | |
wg.Wait() | |
log.Println("Fetched", len(titles), "resources in", time.Since(t)) | |
} | |
func fetch(title string) { | |
log.Println("START fetch", title) | |
// Foil caches | |
trailer := fmt.Sprintf("?foil=%d", rand.Intn(9999)) | |
u := "https://en.wikipedia.org/api/rest_v1/page/summary/" + title + trailer | |
res, err := http.Get(u) | |
if err != nil { | |
log.Println("Error fetching: ", err) | |
} | |
buffer, err := ioutil.ReadAll(res.Body) | |
res.Body.Close() | |
if err != nil { | |
log.Println("Error reading body: ", err) | |
} | |
_ = buffer | |
log.Println("END fetch", title, "->", len(buffer), "bytes") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment