49 lines
1.1 KiB
Go
49 lines
1.1 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"encoding/json"
|
|
"net/http"
|
|
"k3gtpi.jumpingcrab.com/go-learning/pokedexcli/internal/pokecache"
|
|
)
|
|
|
|
func commandMapb(p *PokedexConfig, c *pokecache.Cache) error {
|
|
var baseUrl string
|
|
if p.Previous == nil {
|
|
fmt.Println("you're on the first page")
|
|
return nil
|
|
} else {
|
|
baseUrl = *p.Previous
|
|
}
|
|
var body []byte
|
|
if resp, exists := c.Get(baseUrl); exists {
|
|
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)
|
|
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)
|
|
}
|
|
|
|
c.Add(baseUrl, body)
|
|
}
|
|
if err := json.Unmarshal(body, &p); err != nil {
|
|
return fmt.Errorf("could not unmarshal response! Err: %w", err)
|
|
}
|
|
for _, location := range p.Results {
|
|
fmt.Println(location["name"])
|
|
}
|
|
return nil
|
|
}
|