/
caller.go
90 lines (77 loc) · 2.1 KB
/
caller.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
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.
package client
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"path"
"github.com/elastic/k8s-operators/local-volume/pkg/driver/protocol"
)
const networkProtocol = "unix"
var defaultClientTransport = &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial(networkProtocol, protocol.UnixSocket)
},
}
// Caller wraps an HTTP client so that it can be tweaked.
type Caller struct {
client *http.Client
}
// NewCaller returns a fully initialized HTTP Caller
func NewCaller() Caller {
return Caller{client: NewSocketHTTPClient(nil)}
}
// NewSocketHTTPClient creates a new http.Client with either an explicit set of
// transport settings or de default ones if nil
func NewSocketHTTPClient(t http.RoundTripper) *http.Client {
if t == nil {
t = defaultClientTransport
}
return &http.Client{Transport: t}
}
// Get performs a GET call to the specified path.
func (c *Caller) Get(path string) (string, error) {
resp, err := c.client.Get(buildURL(path))
if err != nil {
return "", err
}
body, err := readBody(resp)
if err != nil {
return "", err
}
return string(body), nil
}
// Post performs a POST call to the specified path and body.
func (c *Caller) Post(path string, reqBody interface{}) (string, error) {
jsonBytes, err := json.Marshal(reqBody)
if err != nil {
return "", err
}
resp, err := c.client.Post(buildURL(path), "", bytes.NewReader(jsonBytes))
if err != nil {
return "", err
}
body, err := readBody(resp)
if err != nil {
return "", err
}
return string(body), nil
}
func buildURL(urlPath string) string {
fullPath := path.Join(networkProtocol, urlPath)
return fmt.Sprintf("http://%s", fullPath)
}
func readBody(resp *http.Response) (string, error) {
body, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
return "", err
}
return string(body), nil
}