forked from nytimes/gizmo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
89 lines (76 loc) · 1.8 KB
/
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package nyt
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"time"
)
type (
Client interface {
GetMostPopular(string, string, uint) ([]*MostPopularResult, error)
SemanticConceptSearch(string, string) ([]*SemanticConceptArticle, error)
}
ClientImpl struct {
mostPopularToken string
semanticToken string
}
)
func NewClient(mostPopToken, semanticToken string) Client {
return &ClientImpl{mostPopToken, semanticToken}
}
func (c *ClientImpl) GetMostPopular(resourceType string, section string, timePeriodDays uint) ([]*MostPopularResult, error) {
var (
res MostPopularResponse
)
uri := fmt.Sprintf("/svc/mostpopular/v2/%s/%s/%d.json?api-key=%s",
resourceType,
section,
timePeriodDays,
c.mostPopularToken)
rawRes, err := c.do(uri)
if err != nil {
return nil, err
}
err = json.Unmarshal(rawRes, &res)
return res.Results, err
}
func (c *ClientImpl) SemanticConceptSearch(conceptType, concept string) ([]*SemanticConceptArticle, error) {
var (
res SemanticConceptResponse
)
uri := fmt.Sprintf("/svc/semantic/v2/concept/name/nytd_%s/%s.json?fields=article_list&api-key=%s",
conceptType,
concept,
c.semanticToken)
rawRes, err := c.do(uri)
if err != nil {
return nil, err
}
err = json.Unmarshal(rawRes, &res)
if len(res.Results) == 0 {
return nil, errors.New("no results")
}
return res.Results[0].ArticleList.Results, nil
}
func (c *ClientImpl) do(uri string) (body []byte, err error) {
hc := http.Client{
Timeout: 5 * time.Second,
}
req, err := http.NewRequest("GET", "https://api.nytimes.com"+uri, nil)
if err != nil {
return nil, err
}
var res *http.Response
res, err = hc.Do(req)
if err != nil {
return nil, err
}
defer func() {
if cerr := res.Body.Close(); cerr != nil && err == nil {
err = cerr
}
}()
return ioutil.ReadAll(res.Body)
}