Skip to content

Instantly share code, notes, and snippets.

@saiumesh535
Last active February 28, 2019 19:51
Show Gist options
  • Save saiumesh535/432d433f70c82b066e2d0ab3492d42c8 to your computer and use it in GitHub Desktop.
Save saiumesh535/432d433f70c82b066e2d0ab3492d42c8 to your computer and use it in GitHub Desktop.
making http calls reading them in golang using goroutines
package main
import (
"encoding/json"
"fmt"
"net/http"
)
type InfoData struct {
Seed string
}
type RandomData struct {
Results interface{}
Info InfoData
}
func randomSeeds(numberOfSeeds int, runner chan string) {
for index := 0; index < numberOfSeeds; index++ {
resp, err := http.Get("https://randomuser.me/api/")
if err != nil {
fmt.Println("error", err)
close(runner)
return
}
defer resp.Body.Close()
var randomData RandomData
err = json.NewDecoder(resp.Body).Decode(&randomData)
if err != nil {
close(runner)
fmt.Println("Some error", err)
return
}
runner <- randomData.Info.Seed
}
defer func(lol chan string) {
close(lol)
}(runner)
}
func main() {
runner := make(chan string)
var seeds []string
go randomSeeds(2, runner)
for seed := range runner {
seeds = append(seeds, seed)
}
fmt.Println("Done!!", seeds)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment