-
Notifications
You must be signed in to change notification settings - Fork 14
/
tweet_counts.go
94 lines (82 loc) · 2.4 KB
/
tweet_counts.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
90
91
92
93
94
package gotwtr
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
)
func countRecentTweets(ctx context.Context, c *client, tweet string, opt ...*TweetCountsOption) (*TweetCountsResponse, error) {
if tweet == "" {
return nil, errors.New("count of recent tweets: tweet parameter is required")
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, countsRecentTweetsURL, nil)
if err != nil {
return nil, fmt.Errorf("count of recent tweets new request with ctx: %w", err)
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.bearerToken))
var topt TweetCountsOption
switch len(opt) {
case 0:
// do nothing
case 1:
topt = *opt[0]
default:
return nil, errors.New("count of recent tweets: only one option is allowed")
}
topt.addQuery(req, tweet)
resp, err := c.client.Do(req)
if err != nil {
return nil, fmt.Errorf("count of recent tweets: %w", err)
}
defer resp.Body.Close()
var tcr TweetCountsResponse
if err := json.NewDecoder(resp.Body).Decode(&tcr); err != nil {
return nil, fmt.Errorf("count of recent tweets: %w", err)
}
if resp.StatusCode != http.StatusOK {
return &tcr, &HTTPError{
APIName: "count of recent tweets",
Status: resp.Status,
URL: req.URL.String(),
}
}
return &tcr, nil
}
func countAllTweets(ctx context.Context, c *client, tweet string, opt ...*TweetCountsAllOption) (*TweetCountsResponse, error) {
if tweet == "" {
return nil, errors.New("count of all tweets: tweet parameter is required")
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, countsAllTweetsURL, nil)
if err != nil {
return nil, fmt.Errorf("count of all tweets new request with ctx: %w", err)
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.bearerToken))
var topt TweetCountsAllOption
switch len(opt) {
case 0:
// do nothing
case 1:
topt = *opt[0]
default:
return nil, errors.New("count of all tweets: only one option is allowed")
}
topt.addQuery(req, tweet)
resp, err := c.client.Do(req)
if err != nil {
return nil, fmt.Errorf("count of all tweets: %w", err)
}
defer resp.Body.Close()
var tcr TweetCountsResponse
if err := json.NewDecoder(resp.Body).Decode(&tcr); err != nil {
return nil, fmt.Errorf("count of all tweets: %w", err)
}
if resp.StatusCode != http.StatusOK {
return &tcr, &HTTPError{
APIName: "count of all tweets",
Status: resp.Status,
URL: req.URL.String(),
}
}
return &tcr, nil
}