This commit is contained in:
49
pokeapi/pokemon_get.go
Normal file
49
pokeapi/pokemon_get.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package pokeapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// GetPokemon -
|
||||
func (c *Client) GetPokemon(pokemonName string) (Pokemon, error) {
|
||||
url := baseURL + "/pokemon/" + pokemonName
|
||||
|
||||
if val, ok := c.cache.Get(url); ok {
|
||||
pokemonResp := Pokemon{}
|
||||
err := json.Unmarshal(val, &pokemonResp)
|
||||
if err != nil {
|
||||
return Pokemon{}, err
|
||||
}
|
||||
return pokemonResp, nil
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("GET", url, nil)
|
||||
if err != nil {
|
||||
return Pokemon{}, err
|
||||
}
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return Pokemon{}, err
|
||||
}
|
||||
defer func(Body io.ReadCloser) {
|
||||
_ = Body.Close()
|
||||
}(resp.Body)
|
||||
|
||||
dat, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return Pokemon{}, err
|
||||
}
|
||||
|
||||
pokemonResp := Pokemon{}
|
||||
err = json.Unmarshal(dat, &pokemonResp)
|
||||
if err != nil {
|
||||
return Pokemon{}, err
|
||||
}
|
||||
|
||||
c.cache.Add(url, dat)
|
||||
|
||||
return pokemonResp, nil
|
||||
}
|
||||
Reference in New Issue
Block a user