-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
157 lines (141 loc) · 4.37 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
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
// Copyright (c) 2017 Epracom Advies.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package restkit
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"net/url"
syspath "path"
"strconv"
)
type RestClient struct {
baseURL *url.URL
client *http.Client
RequestBuilder func(method, path string, query url.Values, reqBody interface{}) (*http.Request, error)
ResultParser func(resp *http.Response, body []byte, result interface{}) error
ErrorParser func(resp *http.Response, body []byte) error
ResponseParser func(resp *http.Response, result interface{}) error
}
func NewRestClient(baseURL *url.URL, client ...*http.Client) *RestClient {
c := &RestClient{
baseURL: baseURL,
}
if len(client) > 0 {
c.client = client[0]
} else {
c.client = http.DefaultClient
}
c.RequestBuilder = c.DefaultRequestBuilder
c.ResultParser = c.DefaultResultParser
c.ErrorParser = c.DefaultErrorParser
c.ResponseParser = c.DefaultResponseParser
return c
}
// Request executes a client request.
// method: GET|POST|PUT|DELETE|HEAD
// path: Path relative to the path of the baseURL
// query: Query string (can be nil)
// reqBody: Object to marshal into the request body
// result: Reference to object to unmarshal the response into
func (c *RestClient) Request(method, path string, query url.Values, reqBody interface{}, result interface{}) error {
req, err := c.RequestBuilder(method, path, query, reqBody)
if err != nil {
return WithStack(err)
}
resp, err := c.client.Do(req)
if err != nil {
return WithStack(err)
}
if err := c.ResponseParser(resp, result); err != nil {
return WithStack(err)
}
return nil
}
// DefaultRequestBuilder implements the default RequestBuilder behavior.
func (c *RestClient) DefaultRequestBuilder(method, path string, query url.Values, reqBody interface{}) (*http.Request, error) {
url := *c.baseURL
url.Path = syspath.Join(url.Path, path)
if query != nil {
url.RawQuery = query.Encode()
}
var reqReader io.Reader
var contentType string
var contentLength string
if reqBody != nil {
content, err := json.Marshal(reqBody)
if err != nil {
return nil, WithStack(err)
}
reqReader = bytes.NewBuffer(content)
contentType = "application/json"
contentLength = strconv.Itoa(len(content))
}
req, err := http.NewRequest(method, url.String(), reqReader)
if err != nil {
return nil, WithStack(err)
}
if contentType != "" {
req.Header.Set("Content-Type", contentType)
}
if contentLength != "" {
req.Header.Set("Content-Length", contentLength)
}
return req, nil
}
// DefaultResponseParser implements the default ResponseParser behavior.
// It reads the response body.
// Then if the status == OK, it tries to parse it into the result.
// Otherwise if the body is not empty, it tries to parse it into an ErrorResponse.
func (c *RestClient) DefaultResponseParser(resp *http.Response, result interface{}) error {
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return WithStack(err)
}
if resp.StatusCode == http.StatusOK {
if err := c.ResultParser(resp, body, result); err != nil {
return WithStack(err)
}
return nil
}
if err := c.ErrorParser(resp, body); err != nil {
return WithStack(err)
}
return nil
}
// DefaultErrorParser tries to parse the given response body into a the given result object.
func (c *RestClient) DefaultResultParser(resp *http.Response, body []byte, result interface{}) error {
if result != nil {
if err := json.Unmarshal(body, result); err != nil {
return WithStack(err)
}
}
return nil
}
// DefaultErrorParser tries to parse the given response body into an ErrorResponse.
func (c *RestClient) DefaultErrorParser(resp *http.Response, body []byte) error {
var er ErrorResponse
if len(body) > 0 {
if err := json.Unmarshal(body, &er); err != nil {
return WithStack(err)
}
} else {
er.TheError.Message = resp.Status
}
er.statusCode = resp.StatusCode
return WithStack(&er)
}