Files
boot-dev-pokedex/pokeapi/location_list.go
2025-03-10 22:20:51 +02:00

53 lines
1009 B
Go

package pokeapi
import (
"encoding/json"
"io"
"net/http"
)
// ListLocations -
func (c *Client) ListLocations(pageURL *string) (RespShallowLocations, error) {
url := baseURL + "/location-area"
if pageURL != nil {
url = *pageURL
}
if val, ok := c.cache.Get(url); ok {
locationsResp := RespShallowLocations{}
err := json.Unmarshal(val, &locationsResp)
if err != nil {
return RespShallowLocations{}, err
}
return locationsResp, nil
}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return RespShallowLocations{}, err
}
resp, err := c.httpClient.Do(req)
if err != nil {
return RespShallowLocations{}, err
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(resp.Body)
dat, err := io.ReadAll(resp.Body)
if err != nil {
return RespShallowLocations{}, err
}
locationsResp := RespShallowLocations{}
err = json.Unmarshal(dat, &locationsResp)
if err != nil {
return RespShallowLocations{}, err
}
c.cache.Add(url, dat)
return locationsResp, nil
}