-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
61 lines (50 loc) · 1.15 KB
/
api.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
)
const (
PokemonAPI = "https://pokeapi.co/api/v2/pokemon"
PokemonSpeciesAPI = "https://pokeapi.co/api/v2/pokemon-species"
)
func fetchPokemonData(pokemon string) PokemonData {
return fetchData[PokemonData](fmt.Sprintf("%s/%s", PokemonAPI, pokemon))
}
func fetchPokemonSpeciesData(pokemon string) PokemonSpeciesData {
return fetchData[PokemonSpeciesData](fmt.Sprintf("%s/%s", PokemonSpeciesAPI, pokemon))
}
func isValidPokemonName(name string) bool {
resp, err := http.Get(fmt.Sprintf("%s/%s", PokemonAPI, name))
if err != nil {
return false
}
defer resp.Body.Close()
return resp.StatusCode == http.StatusOK
}
func fetchData[T any](url string) T {
resp, err := http.Get(url)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
var data T
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
log.Fatal(err)
}
return data
}
func fetchPokemonImage(url string) string {
resp, err := http.Get(url)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
return string(body)
}