-
Notifications
You must be signed in to change notification settings - Fork 26
/
client.go
45 lines (35 loc) · 824 Bytes
/
client.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
package pokeapi
import (
"encoding/json"
"io/ioutil"
"net/http"
"time"
"github.com/patrickmn/go-cache"
)
const apiurl = "https://pokeapi.co/api/v2/"
var c *cache.Cache
func init() {
c = cache.New(defaultCacheSettings.MinExpire, defaultCacheSettings.MaxExpire)
}
func do(endpoint string, obj interface{}) error {
cached, found := c.Get(endpoint)
if found && CacheSettings.UseCache {
return json.Unmarshal(cached.([]byte), &obj)
}
req, err := http.NewRequest(http.MethodGet, apiurl+endpoint, nil)
if err != nil {
return err
}
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
setCache(endpoint, body)
return json.Unmarshal(body, &obj)
}