Files
boot-dev-pokedex/pokeapi/location_get.go
2025-03-10 22:26:13 +02:00

50 lines
882 B
Go

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