forked from wtfutil/wtf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
64 lines (50 loc) · 1.19 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
package jenkins
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
func Create(jenkinsURL string, username string, apiKey string) (*View, error) {
const apiSuffix = "api/json?pretty=true"
parsedSuffix, err := url.Parse(apiSuffix)
if err != nil {
return &View{}, err
}
parsedJenkinsURL, err := url.Parse(ensureLastSlash(jenkinsURL))
if err != nil {
return &View{}, err
}
jenkinsAPIURL := parsedJenkinsURL.ResolveReference(parsedSuffix)
req, err := http.NewRequest("GET", jenkinsAPIURL.String(), nil)
req.SetBasicAuth(username, apiKey)
httpClient := &http.Client{}
resp, err := httpClient.Do(req)
if err != nil {
return &View{}, err
}
view := &View{}
parseJson(view, resp.Body)
return view, nil
}
func ensureLastSlash(URL string) string {
return strings.TrimRight(URL, "/") + "/"
}
/* -------------------- Unexported Functions -------------------- */
func parseJson(obj interface{}, text io.Reader) {
jsonStream, err := ioutil.ReadAll(text)
if err != nil {
panic(err)
}
decoder := json.NewDecoder(bytes.NewReader(jsonStream))
for {
if err := decoder.Decode(obj); err == io.EOF {
break
} else if err != nil {
panic(err)
}
}
}