Last active
February 28, 2019 19:51
-
-
Save saiumesh535/432d433f70c82b066e2d0ab3492d42c8 to your computer and use it in GitHub Desktop.
making http calls reading them in golang using goroutines
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 ( | |
"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