concurrent working

This commit is contained in:
Dan Dobos
2021-11-02 16:32:21 +01:00
parent 43380ec064
commit 7ab57f2ea0
3 changed files with 76 additions and 40 deletions
+43 -7
View File
@@ -5,9 +5,10 @@ import (
"fmt"
"io/ioutil"
"net/http"
"sync"
)
func GetPokemons() (*[]Pokemon, error) {
func GetPokemons() (map[string]*Pokemon, error) {
//get pokemon data from api
resp, err := http.Get("https://pokeapi.co/api/v2/pokemon/?offset=0&limit=500")
@@ -27,10 +28,47 @@ func GetPokemons() (*[]Pokemon, error) {
fmt.Println(err.Error())
}
PokemonSlice := make([]Pokemon, 0)
// PokemonSlice := make([]Pokemon, 0)
// for i := range pokemonsData.Results {
// go func() {
// indPokemon := fetchIndividualPokemons(pokemonsData.Results[i].URL)
// PokemonSlice = append(PokemonSlice, indPokemon)
// }()
// }
PokemonMap := make(map[string]*Pokemon)
pokemonStream := make(chan Pokemon)
var wg sync.WaitGroup
wg.Add(len(pokemonsData.Results))
for i := range pokemonsData.Results {
resp, err := http.Get(pokemonsData.Results[i].URL)
go func(iterator int) {
defer wg.Done()
indPokemon := fetchIndividualPokemons(pokemonsData.Results[iterator].URL)
pokemonStream <- indPokemon
}(i)
}
for range pokemonsData.Results {
p := <-pokemonStream
PokemonMap[p.Name] = &p
}
go func() {
wg.Wait()
close(pokemonStream)
}()
fmt.Print(len(PokemonMap))
return PokemonMap, nil
}
func fetchIndividualPokemons(pokemonURL string) Pokemon {
resp, err := http.Get(pokemonURL)
if err != nil {
fmt.Println(err.Error())
}
@@ -56,15 +94,13 @@ func GetPokemons() (*[]Pokemon, error) {
pokeTypes += pokemonDetails.Types[z].Type.Name + " "
}
PokemonSlice = append(PokemonSlice, Pokemon{
return Pokemon{
Name: pokemonDetails.Name,
Weight: pokemonDetails.Weight,
Height: pokemonDetails.Height,
Moves: pokeMoves,
Types: pokeTypes,
Image: pokemonDetails.Sprites.Other.OfficialArtwork.FrontDefault,
})
}
}
return &PokemonSlice, nil
}
+1 -1
View File
@@ -27,7 +27,7 @@ type Pokemon struct {
type PageData struct {
NavigationLinks []SiteLink
Data []Pokemon
Data map[string]*Pokemon
}
type PokemonMove struct {
+1 -1
View File
@@ -16,7 +16,7 @@ func (s *ApplicationServer) pokemonPageHandler() func(*gin.Context) {
return func(c *gin.Context) {
c.HTML(http.StatusOK, "views/Pokemons.gohtml", pokemongotemplates.PageData{
NavigationLinks: pokemongotemplates.NavigationLinks,
Data: *data,
Data: data,
})
}
}