-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgithub_api.go
97 lines (80 loc) · 2.23 KB
/
github_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
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
95
96
97
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"time"
"github.com/pkg/errors"
"github.com/spf13/viper"
)
type GitHubAPI struct {
httpc *http.Client
user string
token string
}
func NewGitHubAPI() *GitHubAPI {
return &GitHubAPI{
user: viper.GetString("github.user"),
token: viper.GetString("github.token"),
httpc: &http.Client{
Timeout: 10 * time.Second,
},
}
}
func (api GitHubAPI) SearchCommits(query string, page int) (*SearchResults, error) {
params := url.Values{}
params.Add("q", query)
params.Add("sort", "author-date")
params.Add("order", "desc")
params.Add("per_page", "100")
params.Add("page", fmt.Sprint(page))
searchURL, _ := url.Parse("https://api.github.com/search/commits")
searchURL.RawQuery = params.Encode()
req, err := api.authenticatedRequest(http.MethodGet, searchURL.String(), nil)
if err != nil {
return nil, errors.Wrap(err, "failed to build commit search request")
}
var results *SearchResults
if err := api.do(req, &results); err != nil {
return nil, errors.Wrap(err, "failed to search commits")
}
return results, nil
}
func (api GitHubAPI) do(req *http.Request, v interface{}) error {
resp, err := api.httpc.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
if isSecondaryRateLimitReached(resp) {
log.Println("Secondary rate limit reached - making too many requests concurrently")
}
return fmt.Errorf("%s: github api response", resp.Status)
}
err = json.NewDecoder(resp.Body).Decode(&v)
if err != nil {
return errors.Wrap(err, "failed to parse github api response")
}
return nil
}
func (api GitHubAPI) authenticatedRequest(method string, url string, body io.Reader) (*http.Request, error) {
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
req.Header.Add("Accept", "application/vnd.github.cloak-preview")
if api.user != "" && api.token != "" {
debugLog(fmt.Sprintf("Request authenticated as '%s'", api.user))
req.SetBasicAuth(api.user, api.token)
} else {
debugLog("Unauthenticated request")
}
return req, nil
}
func isSecondaryRateLimitReached(res *http.Response) bool {
return res.StatusCode == 403 && res.Header.Get("X-Ratelimit-Remaining") != "0"
}