pokedex_cli/command_map.go

49 lines
1.1 KiB
Go
Raw Normal View History

2025-09-28 20:57:48 +00:00
package main
2025-10-04 17:29:20 +00:00
import (
"encoding/json"
"fmt"
2025-10-04 17:29:20 +00:00
"io"
"net/http"
2025-10-04 17:29:20 +00:00
)
func commandMap(p *PokedexConfig, a *string) error {
2025-10-04 17:29:20 +00:00
var baseUrl string
if p.LocationData.Next == nil {
2025-10-04 17:29:20 +00:00
baseUrl = "https://pokeapi.co/api/v2/location-area/"
} else {
baseUrl = *p.LocationData.Next
2025-10-04 17:29:20 +00:00
}
var body []byte
// Check if respones is available in cache
if resp, exists := p.Cache.Get(baseUrl); exists {
2025-10-04 17:29:20 +00:00
body = resp
} else {
client := &http.Client{}
resp, err := client.Get(baseUrl)
if err != nil {
return fmt.Errorf("could not make request to Pokedex API! Err: %w", err)
}
body, err = io.ReadAll(resp.Body)
2025-10-04 17:29:20 +00:00
defer resp.Body.Close()
if resp.StatusCode > 299 {
return fmt.Errorf("request returned non-200 code! Code: %v Body: %v", resp.StatusCode, body)
}
if err != nil {
return fmt.Errorf("could not read request body! Err: %w", err)
}
p.Cache.Add(baseUrl, body)
2025-10-04 17:29:20 +00:00
}
if err := json.Unmarshal(body, &p.LocationData); err != nil {
2025-10-04 17:29:20 +00:00
return fmt.Errorf("could not unmarshal response! Err: %w", err)
}
for _, location := range p.LocationData.Locations {
2025-10-04 17:29:20 +00:00
fmt.Println(location["name"])
}
2025-09-28 20:57:48 +00:00
return nil
}