-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclient.go
More file actions
122 lines (93 loc) · 1.98 KB
/
Copy pathclient.go
File metadata and controls
122 lines (93 loc) · 1.98 KB
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package gitlab
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/Frontware/GitLabBack/config"
)
const (
defaultBaseURL = "https://gitlab.com/"
apiVersionPath = "api/v4/"
userAgent = "GitLabBack"
)
// Client basic struct for GitLab client
type Client struct {
client *http.Client
baseURL *url.URL
token string
UserAgent string
}
// New creates new GitLab client
func New(conf *config.Config) *Client {
if conf == nil {
return nil
}
c := &Client{
client: http.DefaultClient,
token: conf.Token,
}
if conf.BaseURL != "" {
c.setBaseURL(conf.BaseURL)
} else {
c.setBaseURL(defaultBaseURL)
}
return c
}
// setBaseURL assigns the base url to client
func (c *Client) setBaseURL(urlStr string) error {
if !strings.HasSuffix(urlStr, "/") {
urlStr += "/"
}
baseURL, err := url.Parse(urlStr)
if err != nil {
return err
}
if !strings.HasSuffix(baseURL.Path, apiVersionPath) {
baseURL.Path += apiVersionPath
}
c.baseURL = baseURL
return nil
}
// NewRequest creates a new http request for GitLab api
func (c *Client) NewRequest(method, path string, query map[string]string) (*http.Request, error) {
u := *c.baseURL
unescaped, err := url.PathUnescape(path)
if err != nil {
return nil, err
}
u.Path = u.Path + unescaped
if query != nil {
q := u.Query()
for k, v := range query {
q.Set(k, v)
}
u.RawQuery = q.Encode()
}
req, err := http.NewRequest(method, u.String(), nil)
if err != nil {
return nil, err
}
req.Header.Add("Private-Token", c.token)
req.Header.Add("Accept", "application/json")
req.Header.Add("User-Agent", userAgent)
return req, nil
}
// Do requests the api and store response in struct
func (c *Client) Do(req *http.Request, v interface{}) (err error) {
if v == nil {
return nil
}
resp, err := c.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
err = json.Unmarshal(b, v)
return err
}