-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathclient.go
More file actions
76 lines (62 loc) · 2.25 KB
/
client.go
File metadata and controls
76 lines (62 loc) · 2.25 KB
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
package rclient
import (
"fmt"
"net/http"
)
// RestClient builds, executes, and reads http requests/responses.
type RestClient struct {
Host string
RequestBuilder RequestBuilder
RequestDoer RequestDoer
ResponseReader ResponseReader
RequestOptions []RequestOption
}
// NewRestClient returns a new RestClient with all of the default fields.
// Any of the default fields can be changed with the options param.
func NewRestClient(host string, options ...ClientOption) *RestClient {
r := &RestClient{
Host: host,
RequestBuilder: BuildJSONRequest,
RequestDoer: http.DefaultClient,
ResponseReader: ReadJSONResponse,
RequestOptions: []RequestOption{},
}
for _, option := range options {
option(r)
}
return r
}
// Delete passes its params to RestClient.Do() with the "DELETE" method.
func (r *RestClient) Delete(path string, body, v interface{}, options ...RequestOption) error {
return r.Do("DELETE", path, body, v, options...)
}
// Get passes its params to RestClient.Do() with the "GET" method.
func (r *RestClient) Get(path string, v interface{}, options ...RequestOption) error {
return r.Do("GET", path, nil, v, options...)
}
// Patch passes its params to RestClient.Do() with the "PATCH" method.
func (r *RestClient) Patch(path string, body, v interface{}, options ...RequestOption) error {
return r.Do("PATCH", path, body, v, options...)
}
// Post passes its params to RestClient.Do() with the "POST" method.
func (r *RestClient) Post(path string, body, v interface{}, options ...RequestOption) error {
return r.Do("POST", path, body, v, options...)
}
// Put passes its params to RestClient.Do() with the "PUT" method.
func (r *RestClient) Put(path string, body, v interface{}, options ...RequestOption) error {
return r.Do("PUT", path, body, v, options...)
}
// Do orchestrates building, performing, and reading http requests and responses.
func (r *RestClient) Do(method, path string, body, v interface{}, options ...RequestOption) error {
url := fmt.Sprintf("%s%s", r.Host, path)
options = append(r.RequestOptions, options...)
req, err := r.RequestBuilder(method, url, body, options...)
if err != nil {
return err
}
resp, err := r.RequestDoer.Do(req)
if err != nil {
return err
}
return r.ResponseReader(resp, v)
}