This commit is contained in:
49
pokeapi/location_get.go
Normal file
49
pokeapi/location_get.go
Normal file
@@ -0,0 +1,49 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user