-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
69 lines (60 loc) · 1.7 KB
/
request.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
func execRequest(method string, url string, payload interface{}) (*http.Response, error) {
payloadJSON, err := json.Marshal(&payload)
if err != nil {
return nil, fmt.Errorf("Fail to encode to JSON: %v", err)
}
payloadBuffer := bytes.NewBuffer(payloadJSON)
req, err := http.NewRequest(method, url, payloadBuffer)
if err != nil {
return nil, err
}
if req.Method != "DELETE" {
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
}
if serverConfig.PersonalToken != "" {
req.Header.Set("Authorization", "token "+serverConfig.PersonalToken)
}
return http.DefaultClient.Do(req)
}
// FetchAPI execute GET request to Github API to fetch endPoint parameter
// params each element has to be already formated like key=value
func FetchAPI(endPoint string, params ...string) ([]byte, error) {
queryParam := "?"
first := true
for _, param := range params {
if first {
queryParam += param
first = false
} else {
queryParam += "&" + param
}
}
url := serverConfig.GithubAPIURL + "/" + endPoint
if len(params) > 0 {
url += queryParam
}
resp, err := execRequest("GET", url, nil)
if err != nil {
return nil, fmt.Errorf("Fail to get resource", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 && resp.StatusCode != 201 && resp.StatusCode != 202 {
return nil, fmt.Errorf("Request returned bad status", resp.Status)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("Failed to read body from request", err)
}
remaining := resp.Header.Get("X-RateLimit-Remaining")
fmt.Println("requests remaining:", remaining)
return body, nil
}