-
Notifications
You must be signed in to change notification settings - Fork 234
/
info.go
115 lines (98 loc) · 2.55 KB
/
info.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package info
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"github.com/CircleCI-Public/circleci-cli/api/header"
"github.com/CircleCI-Public/circleci-cli/settings"
"github.com/CircleCI-Public/circleci-cli/version"
)
// InfoClient An interface with all the Info Functions.
type InfoClient interface {
GetInfo() (*[]Organization, error)
}
// errorResponse used to handle error messages from the API.
type errorResponse struct {
Message *string `json:"message"`
}
// InfoRESTClient A restful implementation of the InfoClient
type InfoRESTClient struct {
token string
server string
client *http.Client
}
// organization json org info
type Organization struct {
ID string `json:"id"`
Name string `json:"name"`
}
// GetInfo
func (c *InfoRESTClient) GetInfo() (*[]Organization, error) {
var err error
queryURL, err := url.Parse(c.server)
if err != nil {
return nil, err
}
queryURL, err = queryURL.Parse("me/collaborations")
if err != nil {
return nil, err
}
req, err := c.newHTTPRequest("GET", queryURL.String(), nil)
if err != nil {
return nil, fmt.Errorf("failed to construct new request: %v", err)
}
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
bodyBytes, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
var dest errorResponse
if err := json.Unmarshal(bodyBytes, &dest); err != nil {
return nil, err
}
return nil, errors.New(*dest.Message)
}
orgs := make([]Organization, 0)
if err := json.Unmarshal(bodyBytes, &orgs); err != nil {
return nil, err
}
return &orgs, nil
}
// newHTTPRequest Creates a new standard HTTP request object used to communicate with the API
func (c *InfoRESTClient) newHTTPRequest(method, url string, body io.Reader) (*http.Request, error) {
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
req.Header.Add("circle-token", c.token)
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
req.Header.Add("User-Agent", version.UserAgent())
commandStr := header.GetCommandStr()
if commandStr != "" {
req.Header.Add("Circleci-Cli-Command", commandStr)
}
return req, nil
}
// Creates a new client to talk with the rest info endpoints.
func NewInfoClient(config settings.Config) (InfoClient, error) {
serverURL, err := config.ServerURL()
if err != nil {
return nil, err
}
client := &InfoRESTClient{
token: config.Token,
server: serverURL.String(),
client: config.HTTPClient,
}
return client, nil
}