44 lines
		
	
	
		
			1.0 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			44 lines
		
	
	
		
			1.0 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
package main
 | 
						|
 | 
						|
import (
 | 
						|
	"encoding/json"
 | 
						|
	"fmt"
 | 
						|
	"io"
 | 
						|
	"net/http"
 | 
						|
)
 | 
						|
 | 
						|
func commandExplore(p *PokedexConfig, a *string) error {
 | 
						|
	if *a == "" {
 | 
						|
		return fmt.Errorf("you need to specify an area to explore")
 | 
						|
	}
 | 
						|
	baseUrl := "https://pokeapi.co/api/v2/location-area/" + *a + "/"
 | 
						|
	body, exists := p.Cache.Get(baseUrl)
 | 
						|
	if !exists {
 | 
						|
		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)
 | 
						|
		}
 | 
						|
		p.Cache.Add(baseUrl, body)
 | 
						|
	}
 | 
						|
	if err := json.Unmarshal(body, &p.LocalPokemons); err != nil {
 | 
						|
		return fmt.Errorf("could not unmarshal response! Err: %w", err)
 | 
						|
	}
 | 
						|
 | 
						|
	for _, pokemon := range p.LocalPokemons.PokemonEncounters {
 | 
						|
		fmt.Println(pokemon.PokemonSummary.Name)
 | 
						|
	}
 | 
						|
 | 
						|
	return nil
 | 
						|
}
 |