This repository has been archived by the owner on Nov 17, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
client.go
124 lines (98 loc) · 2.42 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package tugboat
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"golang.org/x/net/context"
)
const AcceptHeader = "application/vnd.tugboat+json; version=1"
type Client struct {
// URL is the base url for the Tugboat API.
URL string
client *http.Client
}
// NewClient returns a new Client instance.
func NewClient(c *http.Client) *Client {
if c == nil {
c = http.DefaultClient
}
return &Client{
client: c,
}
}
// Deploy performs a deployment using a Provider.
func (c *Client) Deploy(ctx context.Context, opts DeployOpts, p Provider) (*Deployment, error) {
return deploy(ctx, opts, p, c)
}
// DeploymentsCreate creates a deployment.
func (c *Client) DeploymentsCreate(opts DeployOpts) (*Deployment, error) {
req, err := c.NewRequest("POST", "/deployments", opts)
if err != nil {
return nil, err
}
var d Deployment
if _, err := c.Do(req, &d); err != nil {
return nil, err
}
return &d, nil
}
// WriteLogs streams the reader to the API creating log lines for each line.
func (c *Client) WriteLogs(d *Deployment, r io.Reader) error {
req, err := c.NewRequest("POST", fmt.Sprintf("/deployments/%s/logs", d.ID), r)
if err != nil {
return err
}
_, err = c.Do(req, nil)
return err
}
// UpdateStatus updates the status of the deployment.
func (c *Client) UpdateStatus(d *Deployment, update StatusUpdate) error {
req, err := c.NewRequest("POST", fmt.Sprintf("/deployments/%s/status", d.ID), update)
if err != nil {
return err
}
_, err = c.Do(req, nil)
return err
}
func (c *Client) Do(req *http.Request, v interface{}) (*http.Response, error) {
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode/100 != 2 {
raw, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return nil, fmt.Errorf("unexpected response: %d - %s", resp.StatusCode, string(raw))
}
if v != nil {
if err := json.NewDecoder(resp.Body).Decode(v); err != nil {
return nil, err
}
}
return resp, nil
}
func (c *Client) NewRequest(method, path string, v interface{}) (*http.Request, error) {
var r io.Reader
switch v := v.(type) {
case io.Reader:
r = v
default:
buf := new(bytes.Buffer)
if err := json.NewEncoder(buf).Encode(v); err != nil {
return nil, err
}
r = buf
}
req, err := http.NewRequest(method, c.URL+path, r)
if err != nil {
return req, err
}
req.Header.Set("Accept", AcceptHeader)
return req, err
}