Created
July 19, 2019 20:31
-
-
Save marcosinger/6e67d406b7c8f10f3a72d3d57fe37155 to your computer and use it in GitHub Desktop.
Example of "errgroup" package
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 main | |
import ( | |
"fmt" | |
"net/http" | |
"time" | |
"golang.org/x/sync/errgroup" | |
) | |
type response struct { | |
URL string | |
StatusCode int | |
ElapsedTimeInSeconds float64 | |
} | |
func main() { | |
var ( | |
g errgroup.Group | |
urls = []string{ | |
"http://www.golang.org", | |
"http://www.globoesporte.globo.com", | |
"http://www.hackernews.com", | |
} | |
) | |
// channel to communicate with goroutines | |
output := make(chan response, len(urls)) | |
for _, url := range urls { | |
url := url | |
g.Go(func() error { | |
// fetch the URL | |
start := time.Now() | |
resp, err := http.Get(url) | |
if err != nil { | |
return err | |
} | |
defer resp.Body.Close() | |
output <- response{ | |
URL: url, | |
StatusCode: resp.StatusCode, | |
ElapsedTimeInSeconds: time.Now().Sub(start).Seconds(), | |
} | |
return nil | |
}) | |
} | |
// create an anonymous function to handle with sync and close the given channel | |
go func() { | |
g.Wait() | |
close(output) | |
}() | |
// this range will be printed as soon as we get data into output channel | |
for o := range output { | |
fmt.Printf("%s (%d): %.2f seconds\n", | |
o.URL, o.StatusCode, o.ElapsedTimeInSeconds, | |
) | |
} | |
// the output will be something like: | |
// | |
// http://www.globoesporte.globo.com (200): 2.09 seconds | |
// http://www.hackernews.com (200): 2.10 seconds | |
// http://www.golang.org (200): 2.56 seconds | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment