-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.go
91 lines (74 loc) · 1.85 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
package livy
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"runtime"
"time"
"github.com/pkg/errors"
)
const (
apiVersion = "0.6.0-incubating"
libraryVersion = "0.2.0"
mediaType = "application/json"
)
type Client struct {
client *http.Client
baseURL *url.URL
userAgent string
}
func NewClient(baseURL string, timeout time.Duration) *Client {
u, _ := url.Parse(baseURL)
return &Client{
client: &http.Client{
Timeout: timeout,
},
baseURL: u,
userAgent: fmt.Sprintf("go-livy/%s livy/%s %s (%s/%s)", libraryVersion, apiVersion, runtime.Version(), runtime.GOOS, runtime.GOARCH),
}
}
func (c *Client) NewRequest(method, resource string, payload interface{}) (*http.Request, error) {
rel, err := url.Parse(resource)
if err != nil {
return nil, err
}
u := c.baseURL.ResolveReference(rel)
payloadBytes, err := json.Marshal(payload)
if err != nil {
return nil, errors.Wrap(err, "marshalling JSON")
}
req, err := http.NewRequest(method, u.String(), bytes.NewBuffer(payloadBytes))
if err != nil {
return nil, err
}
req.Header.Add("Accept", mediaType)
req.Header.Add("User-Agent", c.userAgent)
req.Header.Add("X-Requested-By", "bilcus/livy-api-go-client")
return req, nil
}
func (c *Client) Do(req *http.Request, into interface{}) error {
resp, err := c.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return errors.Wrap(err, "reading response body")
}
switch resp.StatusCode {
case http.StatusOK, http.StatusCreated, http.StatusAccepted:
if into == nil {
return nil
}
if err := json.Unmarshal(body, into); err != nil {
return errors.Wrap(err, "decoding response body")
}
return nil
default:
return errors.Errorf("server returned status: %s: %s", resp.Status, extractErrorMessage(body))
}
}