-
Notifications
You must be signed in to change notification settings - Fork 0
/
backend.go
196 lines (158 loc) · 4.28 KB
/
backend.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
package pipekit
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"path"
"strings"
)
var (
defaultBaseURI string = "https://pipekit.io/api"
defaultClusterBaseURI string = "http://localhost:8080/api"
)
// Backend exposes for methods for calling pipekit apis
type Backend interface {
Call(ctx context.Context, method, path string, params ParamsContainer, obj interface{}) error
}
type backend struct {
baseURI string
clusterBaseURI string
httpClient *http.Client
}
// BackendConfig helps configure a new pipekit backend
type BackendConfig struct {
BaseURI *string
ClusterBaseURI *string
HTTPClient *http.Client
}
// NewBackend instantiates a new backend
func NewBackend(config *BackendConfig) Backend {
if config == nil {
config = newDefaultConfig()
}
if config.BaseURI == nil {
config.BaseURI = &defaultBaseURI
}
if config.ClusterBaseURI == nil {
config.ClusterBaseURI = &defaultClusterBaseURI
}
if config.HTTPClient == nil {
config.HTTPClient = &http.Client{}
}
return &backend{
baseURI: *config.BaseURI,
clusterBaseURI: *config.ClusterBaseURI,
httpClient: config.HTTPClient,
}
}
func newDefaultConfig() *BackendConfig {
httpClient := http.Client{}
return &BackendConfig{
BaseURI: &defaultBaseURI,
ClusterBaseURI: &defaultClusterBaseURI,
HTTPClient: &httpClient,
}
}
// Call invokes the backend for a pipekit api
func (b *backend) Call(ctx context.Context, method, path string, params ParamsContainer, body interface{}) error {
formattedPath, err := b.formatURL(path, params)
if err != nil {
return err
}
req, err := formatJSONRequest(ctx, method, formattedPath, body)
if err != nil {
return err
}
_, err = executeRequest(b.httpClient, req, body)
return err
}
// formatURL does two things:
// 1. prepends the base URI to the path - any calls to the pipekit daemon
// are routed to the cluster base uri, and
// 2. appends the query params
func (b *backend) formatURL(urlPath string, params ParamsContainer) (string, error) {
uri := b.baseURI
if strings.Contains(urlPath, "plumbing") {
uri = b.clusterBaseURI
}
u, err := url.Parse(uri)
if err != nil {
return "", nil
}
u.Path = path.Join(u.Path, urlPath)
u.RawQuery = params.GetParams().Values.Encode()
return u.String(), nil
}
// executeRequest executes the formatted request
func executeRequest(client *http.Client, request *http.Request, obj interface{}) (*int, error) {
var err error
resp, err := client.Do(request)
if err != nil {
return nil, err
}
defer func() {
err = resp.Body.Close()
}()
if obj != nil {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
err = json.Unmarshal(body, obj)
if err != nil {
return nil, err
}
}
err = makeErrorIf400sOr500sStatus(resp.StatusCode)
if err != nil {
return nil, err
}
return &resp.StatusCode, nil
}
// makeErrorIf400sOr500sStatus generates an error if the http status code reads
// an error
func makeErrorIf400sOr500sStatus(statusCode int) error {
if statusCode >= http.StatusBadRequest {
return fmt.Errorf("HTTP status: %d", statusCode)
}
return nil
}
// formatJSONRequest formats a JSON request
func formatJSONRequest(ctx context.Context, method, url string, body interface{}) (*http.Request, error) {
jsonBytes, err := json.Marshal(body)
if err != nil {
return nil, err
}
req, err := http.NewRequest(method, url, bytes.NewBuffer(jsonBytes))
if err != nil {
return nil, err
}
req.Close = true
formatJSONHeader(ctx, req)
return req, nil
}
func formatJSONHeader(ctx context.Context, req *http.Request) {
req.Header.Set("Content-Type", "application/json")
// TODO: Get proper context/token passing
// tokenString, ok := GetAuthTokenFromContext(ctx)
// if !ok {
// return
// }
// bearerToken := guaranteeBearerPrefix(tokenString)
bearerToken := "placeholder"
req.Header.Set("Authorization", bearerToken)
}
// FormatURLPath is a convenience method for ensuring that paths are properly
// formatted
func FormatURLPath(format string, params ...string) string {
// Convert parameters to interface{} and URL-escape them
untypedParams := make([]interface{}, len(params))
for i, param := range params {
untypedParams[i] = interface{}(url.QueryEscape(param))
}
return fmt.Sprintf(format, untypedParams...)
}