Skip to content

Instantly share code, notes, and snippets.

@kaneshin
Created January 12, 2016 15:56
Show Gist options
  • Save kaneshin/0e3476861aea6cdb6146 to your computer and use it in GitHub Desktop.
Save kaneshin/0e3476861aea6cdb6146 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"sync"
)
func stargazers(id string) (int, error) {
// https://api.github.com/repos/[username]/[repository]
url := fmt.Sprintf("https://api.github.com/repos/%s", id)
// Request API to fetch object.
resp, err := http.Get(url)
if err != nil {
return 0, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return 0, err
}
// Apply object from the response body as a JSON.
data := map[string]interface{}{}
err = json.Unmarshal(body, &data)
if err != nil {
return 0, err
}
if v, ok := data["stargazers_count"].(float64); ok {
return int(v), nil
}
return 0, nil
}
func main() {
list := []string{
"golang/go",
"golang/mobile",
"apple/swift",
"python/cpython",
"django/django",
}
fmt.Println("\nprintStar")
for _, id := range list {
printStar(id)
}
fmt.Println("\nprintStarWithChannel")
printStarWithChannel(list)
fmt.Println("\nprintStarWithWaitGroup")
printStarWithWaitGroup(list)
}
func printStar(id string) {
star, err := stargazers(id)
if err != nil {
fmt.Fprintln(os.Stderr, err)
} else {
fmt.Println(id, star)
}
}
func printStarWithChannel(list []string) {
var (
done = make(chan bool)
concurrency = 0
)
for _, id := range list {
concurrency++
go func(id string, done chan bool) {
printStar(id)
done <- true
}(id, done)
}
for i := 0; i < concurrency; i++ {
<-done
}
}
func printStarWithWaitGroup(list []string) {
var (
wg = new(sync.WaitGroup)
)
for _, id := range list {
wg.Add(1)
go func(id string) {
printStar(id)
wg.Done()
}(id)
}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment