/
github.go
90 lines (72 loc) · 1.68 KB
/
github.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
package util
import (
"fmt"
"io/ioutil"
"net/http"
)
type Github struct {
token string
userAgent string
}
const Github404 = GithubError("github: 404")
type GithubError string
func (e GithubError) Error() string { return string(e) }
func NewGithub(token, userAgent string) (github *Github) {
return &Github{
token: token,
userAgent: userAgent,
}
}
func (github *Github) Test() (err error) {
// Create a new request using http
req, err := http.NewRequest("GET", "https://api.github.com/zen", nil)
if err != nil {
return
}
// add authorization header to the req
if github.token != "" {
req.Header.Add("Authorization", "token "+github.token)
}
req.Header.Add("User-Agent", github.userAgent)
// Send req using http Client
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
err = fmt.Errorf("test github failed with code %d", resp.StatusCode)
return
}
_, err = ioutil.ReadAll(resp.Body)
return
}
func (github *Github) GetDist(url string) (resp *http.Response, err error) {
// Get dist
// Create a new request using http
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return
}
// add authorization header to the req
if github.token != "" {
req.Header.Add("Authorization", "token "+github.token)
}
req.Header.Add("User-Agent", github.userAgent)
// Send req using http Client
client := &http.Client{}
resp, err = client.Do(req)
if err != nil {
return
}
if resp.StatusCode == 404 {
err = Github404
return
}
if resp.StatusCode != 200 {
err = fmt.Errorf("request github dist(%s) failed with code %d", url, resp.StatusCode)
return
}
return
}