/
client.go
108 lines (92 loc) · 2.31 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package bapi
import (
"bytes"
"encoding/json"
"errors"
"log"
"net/http"
"strconv"
"text/template"
//"io/ioutil"
"fmt"
"net/http/httputil"
)
const (
debugOn = false
)
type BClient struct {
ConsumerKey string
ConsumerSecret string
Repo string
Username string
accessToken *accessToken
}
func (c *BClient) Authenticate() {
accessToken, err := createAccessToken(c)
if err != nil {
log.Printf("%+v", err)
panic("\nAuthentication failure")
}
c.accessToken = accessToken
}
func (c *BClient) PullRequests(status PullRequestStatus) *PullRequestList {
data := PullRequestList{}
urlParams := c.defaultUrlParams()
urlParams["Status"] = status.String()
c.get("https://api.bitbucket.org/2.0/repositories/{{.Username}}/{{.Repo}}/pullrequests?state={{.Status}}", &data, urlParams)
return &data
}
func (c *BClient) PullRequest(id int) *PullRequest {
data := PullRequest{}
urlParams := c.defaultUrlParams()
urlParams["Id"] = strconv.Itoa(id)
c.get("https://api.bitbucket.org/2.0/repositories/{{.Username}}/{{.Repo}}/pullrequests/{{.Id}}", &data, &urlParams)
return &data
}
func (c *BClient) defaultUrlParams() (params map[string]interface{}) {
urlParams := make(map[string]interface{})
urlParams["Username"] = c.Username
urlParams["Repo"] = c.Repo
return urlParams
}
func getUrl(url string, urlData interface{}) string {
tmpl, err := template.New("url").Parse(url)
if err != nil {
panic(err)
}
var doc bytes.Buffer
err = tmpl.Execute(&doc, urlData)
if err != nil {
panic(err)
}
return doc.String()
}
func (c *BClient) get(url string, data, urlData interface{}) error {
rUrl := getUrl(url, urlData)
req, _ := http.NewRequest("GET", rUrl, nil)
signDataRequest(req, c.accessToken, c.ConsumerKey, c.ConsumerSecret)
if debugOn {
debug(httputil.DumpRequestOut(req, true))
}
resp, err := http.DefaultClient.Do(req)
defer resp.Body.Close()
if debugOn {
debug(httputil.DumpResponse(resp, true))
log.Println("response code:", resp.StatusCode)
}
if resp.StatusCode != 200 {
log.Println("response code:", resp.StatusCode, resp.Status)
return errors.New("Http Status != 200")
}
if err != nil {
return err
}
return json.NewDecoder(resp.Body).Decode(data)
}
func debug(data []byte, err error) {
if err == nil {
fmt.Printf("%s\n\n", data)
} else {
log.Fatalf("%s\n\n", err)
}
}