-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhttp_client.go
220 lines (195 loc) · 4.88 KB
/
http_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
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package httpclient
import (
"encoding/json"
"strings"
"time"
"fmt"
"net/http"
"net/url"
"github.com/pkg/errors"
"gopkg.in/h2non/gentleman.v2"
"gopkg.in/h2non/gentleman.v2/plugin"
"gopkg.in/h2non/gentleman.v2/plugins/query"
"gopkg.in/h2non/gentleman.v2/plugins/timeout"
)
// Client is the HTTP client.
type Client struct {
apiURL *url.URL
httpClient *gentleman.Client
reqUpdaters []func(*gentleman.Request) (*gentleman.Request, error)
}
// New returns a keycloak client.
func New(addrAPI string, reqTimeout time.Duration, reqUpdaters ...func(*gentleman.Request) (*gentleman.Request, error)) (*Client, error) {
var uAPI *url.URL
{
var err error
uAPI, err = url.Parse(addrAPI)
if err != nil {
return nil, errors.Wrap(err, MsgErrCannotParse+"."+PrmAPIURL)
}
}
var httpClient = gentleman.New()
{
httpClient = httpClient.URL(uAPI.String())
httpClient = httpClient.Use(timeout.Request(reqTimeout))
}
var client = &Client{
apiURL: uAPI,
httpClient: httpClient,
reqUpdaters: reqUpdaters,
}
return client, nil
}
// applyPlugins apply all the plugins to the request req, apply also includes internal reqUpdaters
func (c *Client) applyPlugins(req *gentleman.Request, plugins ...plugin.Plugin) (*gentleman.Request, error) {
var err error
for _, p := range plugins {
req = req.Use(p)
}
for _, updater := range c.reqUpdaters {
req, err = updater(req)
if err != nil {
return nil, err
}
}
return req, nil
}
func (c *Client) checkError(resp *gentleman.Response) error {
switch {
case resp.StatusCode == http.StatusUnauthorized:
return HTTPError{
StatusCode: resp.StatusCode,
Message: string(resp.Bytes()),
}
case resp.StatusCode >= 400:
return treatErrorStatus(resp)
case resp.StatusCode >= 200:
return nil
default:
return HTTPError{
StatusCode: resp.StatusCode,
Message: string(resp.Bytes()),
}
}
}
func (c *Client) readContent(resp *gentleman.Response, data interface{}) error {
var hdr = resp.Header.Get("Content-Type")
switch strings.Split(hdr, ";")[0] {
case "application/json":
return resp.JSON(data)
case "text/plain":
*(data.(*string)) = resp.String()
return nil
case "text/html":
*(data.(*string)) = resp.String()
return nil
case "application/octet-stream", "application/zip", "application/pdf", "text/xml":
*(data.(*[]byte)) = resp.Bytes()
return nil
default:
if len(resp.Bytes()) == 0 {
return nil
}
return fmt.Errorf("%s.%v", MsgErrUnkownHTTPContentType, hdr)
}
}
// Get is a HTTP GET method.
func (c *Client) Get(data interface{}, plugins ...plugin.Plugin) error {
var err error
var req = c.httpClient.Get()
req, err = c.applyPlugins(req, plugins...)
if err != nil {
return err
}
var resp *gentleman.Response
{
resp, err = req.Do()
if err != nil {
return errors.Wrap(err, MsgErrCannotObtain+"."+PrmResponse)
}
err = c.checkError(resp)
if err != nil {
return err
}
return c.readContent(resp, data)
}
}
// Post is a HTTP POST method
func (c *Client) Post(data interface{}, plugins ...plugin.Plugin) (string, error) {
var err error
var req = c.httpClient.Post()
req, err = c.applyPlugins(req, plugins...)
if err != nil {
return "", err
}
var resp *gentleman.Response
{
resp, err = req.Do()
if err != nil {
return "", errors.Wrap(err, MsgErrCannotObtain+"."+PrmResponse)
}
err = c.checkError(resp)
if err != nil {
return "", err
}
return resp.Header.Get("Location"), c.readContent(resp, data)
}
}
// Delete is a HTTP DELETE method
func (c *Client) Delete(plugins ...plugin.Plugin) error {
var err error
var req = c.httpClient.Delete()
req, err = c.applyPlugins(req, plugins...)
if err != nil {
return err
}
var resp *gentleman.Response
{
resp, err = req.Do()
if err != nil {
return errors.Wrap(err, MsgErrCannotObtain+"."+PrmResponse)
}
return c.checkError(resp)
}
}
// Put is a HTTP PUT method
func (c *Client) Put(plugins ...plugin.Plugin) error {
var err error
var req = c.httpClient.Put()
req, err = c.applyPlugins(req, plugins...)
if err != nil {
return err
}
var resp *gentleman.Response
{
resp, err = req.Do()
if err != nil {
return errors.Wrap(err, MsgErrCannotObtain+"."+PrmResponse)
}
return c.checkError(resp)
}
}
// CreateQueryPlugins create query parameters with the key values paramKV.
func CreateQueryPlugins(paramKV ...string) []plugin.Plugin {
var plugins = []plugin.Plugin{}
for i := 0; i+1 < len(paramKV); i += 2 {
var k = paramKV[i]
var v = paramKV[i+1]
plugins = append(plugins, query.Add(k, v))
}
return plugins
}
func treatErrorStatus(resp *gentleman.Response) error {
var response map[string]interface{}
err := json.Unmarshal(resp.Bytes(), &response)
if message, ok := response["errorMessage"]; ok && err == nil {
return HTTPError{
StatusCode: resp.StatusCode,
Message: message.(string),
}
}
return HTTPError{
StatusCode: resp.StatusCode,
Message: string(resp.Bytes()),
}
}