-
Notifications
You must be signed in to change notification settings - Fork 0
/
github.go
95 lines (78 loc) · 2.33 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
91
92
93
94
95
package github
import (
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/adamliesko/go-thanks/discover"
)
const apiEndpoint = "https://api.github.com"
// Thanker is a light Github API HTTP client capable of starring a repository.
type Thanker struct {
cl *http.Client
apiToken string
apiEndpoint string
}
// New creates a new thanker with the apiToken set.
func New(token string) Thanker {
return Thanker{
cl: &http.Client{Timeout: 10 * time.Second},
apiToken: token,
apiEndpoint: apiEndpoint,
}
}
// Auth checks whether thanker's apiToken is a valid one for Github.
func (t Thanker) Auth() error {
uri := fmt.Sprintf("%s/%s", t.apiEndpoint, t.authTokenParams())
req, err := http.NewRequest("GET", uri, nil)
if err != nil {
return err
}
resp, err := t.cl.Do(req)
if err != nil {
return fmt.Errorf("github authentication failed with an errror: %v", err)
}
defer resp.Body.Close()
if code := resp.StatusCode; code != http.StatusOK {
return fmt.Errorf("github authentication failed with HTTP status code: %d", code)
}
return nil
}
// Thank stars a repository as user thanker's apiToken.
func (t Thanker) Thank(r discover.Repository) error {
uri, err := t.thankURL(r)
if err != nil {
return err
}
req, err := http.NewRequest("PUT", uri, nil)
if err != nil {
return err
}
// Note that you'll need to set Content-Length to zero when calling out to this endpoint.
req.ContentLength = 0
resp, err := t.cl.Do(req)
if err != nil {
return fmt.Errorf("github starring repo %s failed with an errror: %v", r.URL, err)
}
defer resp.Body.Close()
if code := resp.StatusCode; code != http.StatusNoContent {
return fmt.Errorf("github starring repo %s failed with HTTP status code %d", r.URL, code)
}
return nil
}
// CanThank reports, whether Github thanke is capable of thanking to repository r, by checking package prefix.
func (t Thanker) CanThank(r discover.Repository) bool {
return strings.HasPrefix(r.URL, "github.com")
}
func (t Thanker) authTokenParams() string {
return fmt.Sprintf("?access_token=%s", t.apiToken)
}
func (t Thanker) thankURL(r discover.Repository) (string, error) {
urlString := fmt.Sprintf("%s/user/starred/%s/%s%s", t.apiEndpoint, r.Owner, r.Name, t.authTokenParams())
uri, err := url.Parse(urlString)
if err != nil {
return "", err
}
return uri.String(), nil
}