forked from harness/gitness
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gitlab.go
96 lines (80 loc) · 1.86 KB
/
gitlab.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
package client
import (
"bytes"
"crypto/tls"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
type Client struct {
BaseUrl string
ApiPath string
Token string
Client *http.Client
}
func New(baseUrl, apiPath, token string, skipVerify bool) *Client {
config := &tls.Config{InsecureSkipVerify: skipVerify}
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSClientConfig: config,
}
client := &http.Client{Transport: tr}
return &Client{
BaseUrl: baseUrl,
ApiPath: apiPath,
Token: token,
Client: client,
}
}
func (c *Client) ResourceUrl(u string, params, query QMap) (string, string) {
if params != nil {
for key, val := range params {
u = strings.Replace(u, key, encodeParameter(val), -1)
}
}
query_params := url.Values{}
if query != nil {
for key, val := range query {
query_params.Set(key, val)
}
}
u = c.BaseUrl + c.ApiPath + u + "?" + query_params.Encode()
p, err := url.Parse(u)
if err != nil {
return u, ""
}
opaque := "//" + p.Host + p.Path
return u, opaque
}
func (c *Client) Do(method, url, opaque string, body []byte) ([]byte, error) {
var req *http.Request
var err error
if body != nil {
reader := bytes.NewReader(body)
req, err = http.NewRequest(method, url, reader)
} else {
req, err = http.NewRequest(method, url, nil)
}
if err != nil {
return nil, fmt.Errorf("Error while building gitlab request")
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.Token))
if len(opaque) > 0 {
req.URL.Opaque = opaque
}
resp, err := c.Client.Do(req)
if err != nil {
return nil, fmt.Errorf("Client.Do error: %q", err)
}
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("%s", err)
}
if resp.StatusCode >= 400 {
err = fmt.Errorf("*Gitlab.buildAndExecRequest failed: <%d> %s", resp.StatusCode, req.URL)
}
return contents, err
}