-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpokemon.go
More file actions
55 lines (47 loc) · 996 Bytes
/
pokemon.go
File metadata and controls
55 lines (47 loc) · 996 Bytes
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
package client
import (
"context"
"encoding/json"
"net/http"
)
func (c *Client) GetPokemonByName(
ctx context.Context,
pokemonName string,
) (Pokemon, error) {
req, err := http.NewRequestWithContext(
ctx,
http.MethodGet,
c.apiURL+"/api/v2/pokemon/"+pokemonName,
nil,
)
if err != nil {
return Pokemon{}, PokemonFetchErr{
Message: err.Error(),
StatusCode: -1,
}
}
req.Header.Add("Accept", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return Pokemon{}, PokemonFetchErr{
Message: err.Error(),
StatusCode: -1,
}
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return Pokemon{}, PokemonFetchErr{
Message: "non-200 status code from the API",
StatusCode: resp.StatusCode,
}
}
var pokemon Pokemon
err = json.NewDecoder(resp.Body).Decode(&pokemon)
if err != nil {
return Pokemon{}, PokemonFetchErr{
Message: err.Error(),
StatusCode: resp.StatusCode,
}
}
return pokemon, nil
}