This repository was archived by the owner on Dec 19, 2022. It is now read-only.
forked from leominov/gitlab-project-settings
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
101 lines (89 loc) · 2.15 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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
)
type Client struct {
baseURL string
token string
c *http.Client
}
func NewClient(baseURL, token string) *Client {
httpClient := http.DefaultClient
httpClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
return &Client{
baseURL: baseURL,
token: token,
c: httpClient,
}
}
func (c *Client) getPath(path string) string {
separator := "?"
if strings.Contains(path, separator) {
separator = "&"
}
return fmt.Sprintf("%s/%s%sprivate_token=%s", c.baseURL, path, separator, c.token)
}
func (c *Client) doRequest(method, path string, body interface{}) (*http.Response, error) {
var buf io.Reader
if body != nil {
b, err := json.Marshal(body)
if err != nil {
return nil, err
}
buf = bytes.NewBuffer(b)
}
req, err := http.NewRequest(method, c.getPath(path), buf)
if err != nil {
return nil, fmt.Errorf("Error querying %s", path)
}
req.Header.Add("Content-Type", "application/json")
req.Close = true
return c.c.Do(req)
}
func (c *Client) doFormRequest(method, path string, values map[string]interface{}) ([]byte, error) {
s, err := json.Marshal(values)
if err != nil {
return nil, err
}
b := bytes.NewBuffer(s)
req, err := http.NewRequest(method, c.getPath(path), b)
if err != nil {
return nil, fmt.Errorf("Error querying %s", path)
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.c.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
r, err := ioutil.ReadAll(resp.Body)
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return nil, fmt.Errorf("return code not 2XX: %s, message: %s", resp.Status, string(r))
}
if err != nil {
return nil, err
}
return r, nil
}
func InterfaceMapToStringMap(i map[interface{}]interface{}) map[string]string {
m := make(map[string]string)
for k, v := range i {
m[k.(string)] = v.(string)
}
return m
}
func InterfaceMapToInterfaceMap(i map[interface{}]interface{}) map[string]interface{} {
m := make(map[string]interface{})
for k, v := range i {
m[k.(string)] = v
}
return m
}