-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgoss.go
83 lines (72 loc) · 1.76 KB
/
goss.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
package goss
import (
"bytes"
"context"
"encoding/json"
"fmt"
"golang.org/x/oauth2"
"io/ioutil"
"net/http"
"net/url"
)
type Client struct {
client *http.Client
BaseURL *url.URL
Instances InstancesServiceOp
Plans PlansServiceOp
}
func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) {
u, err := c.BaseURL.Parse(urlStr)
if err != nil {
return nil, err
}
buf := new(bytes.Buffer)
if body != nil {
err = json.NewEncoder(buf).Encode(body)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
req.Header.Add("User-Agent", "goss")
return req, nil
}
func (c *Client) Do(ctx context.Context, request *http.Request, v interface{}) error {
response, err := c.client.Do(request.WithContext(ctx))
if err != nil {
return err
}
defer func() {
if rerr := response.Body.Close(); rerr != nil {
err = rerr
}
}()
if response.StatusCode < 200 || response.StatusCode >= 300 {
return fmt.Errorf("err: %s", response.Status)
}
if response.StatusCode == http.StatusNoContent {
return nil
}
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
return json.Unmarshal(body, v)
}
func NewClientFromToken(apiKey string) *Client {
return NewClient("https://api.scalechamp.com", apiKey)
}
func NewClient(baseUrl, apiKey string) *Client {
sourceToken := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: apiKey})
client := oauth2.NewClient(context.Background(), sourceToken)
u, _ := url.Parse(baseUrl)
c := &Client{client: client, BaseURL: u}
c.Instances = &Instances{client: c}
c.Plans = &Plans{client: c}
return c
}