forked from meilisearch/meilisearch-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_request.go
203 lines (169 loc) · 5.12 KB
/
client_request.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
package meilisearch
import (
"fmt"
"io"
"net/http"
"net/url"
"github.com/valyala/fasthttp"
"encoding/json"
)
const (
contentTypeJSON string = "application/json"
contentTypeNDJSON string = "application/x-ndjson"
contentTypeCSV string = "text/csv"
)
type internalRequest struct {
endpoint string
method string
contentType string
withRequest interface{}
withResponse interface{}
withQueryParams map[string]string
acceptedStatusCodes []int
functionName string
}
func (c *Client) executeRequest(req internalRequest) error {
internalError := &Error{
Endpoint: req.endpoint,
Method: req.method,
Function: req.functionName,
RequestToString: "empty request",
ResponseToString: "empty response",
MeilisearchApiError: meilisearchApiError{
Message: "empty Meilisearch message",
},
StatusCodeExpected: req.acceptedStatusCodes,
}
response := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(response)
err := c.sendRequest(&req, internalError, response)
if err != nil {
return err
}
internalError.StatusCode = response.StatusCode()
err = c.handleStatusCode(&req, response, internalError)
if err != nil {
return err
}
err = c.handleResponse(&req, response, internalError)
if err != nil {
return err
}
return nil
}
func (c *Client) sendRequest(req *internalRequest, internalError *Error, response *fasthttp.Response) error {
var (
request *fasthttp.Request
err error
)
// Setup URL
requestURL, err := url.Parse(c.config.Host + req.endpoint)
if err != nil {
return fmt.Errorf("unable to parse url: %w", err)
}
// Build query parameters
if req.withQueryParams != nil {
query := requestURL.Query()
for key, value := range req.withQueryParams {
query.Set(key, value)
}
requestURL.RawQuery = query.Encode()
}
request = fasthttp.AcquireRequest()
defer fasthttp.ReleaseRequest(request)
request.SetRequestURI(requestURL.String())
request.Header.SetMethod(req.method)
if req.withRequest != nil {
if req.method == http.MethodGet || req.method == http.MethodHead {
return fmt.Errorf("sendRequest: request body is not expected for GET and HEAD requests")
}
if req.contentType == "" {
return fmt.Errorf("sendRequest: request body without Content-Type is not allowed")
}
rawRequest := req.withRequest
if bytes, ok := rawRequest.([]byte); ok {
// If the request body is already a []byte then use it directly
request.SetBody(bytes)
} else if reader, ok := rawRequest.(io.Reader); ok {
// If the request body is an io.Reader then stream it directly until io.EOF
// NOTE: Avoid using this, due to problems with streamed request bodies
request.SetBodyStream(reader, -1)
} else {
// Otherwise convert it to JSON
var (
data []byte
err error
)
if marshaler, ok := rawRequest.(json.Marshaler); ok {
data, err = marshaler.MarshalJSON()
} else {
data, err = json.Marshal(rawRequest)
}
internalError.RequestToString = string(data)
if err != nil {
return internalError.WithErrCode(ErrCodeMarshalRequest, err)
}
request.SetBody(data)
}
}
// adding request headers
if req.contentType != "" {
request.Header.Set("Content-Type", req.contentType)
}
if c.config.APIKey != "" {
request.Header.Set("Authorization", "Bearer "+c.config.APIKey)
}
request.Header.Set("User-Agent", GetQualifiedVersion())
// request is sent
if c.config.Timeout != 0 {
err = c.httpClient.DoTimeout(request, response, c.config.Timeout)
} else {
err = c.httpClient.Do(request, response)
}
// request execution timeout
if err == fasthttp.ErrTimeout {
return internalError.WithErrCode(MeilisearchTimeoutError, err)
}
// request execution fail
if err != nil {
return internalError.WithErrCode(MeilisearchCommunicationError, err)
}
return nil
}
func (c *Client) handleStatusCode(req *internalRequest, response *fasthttp.Response, internalError *Error) error {
if req.acceptedStatusCodes != nil {
// A successful status code is required so check if the response status code is in the
// expected status code list.
for _, acceptedCode := range req.acceptedStatusCodes {
if response.StatusCode() == acceptedCode {
return nil
}
}
// At this point the response status code is a failure.
rawBody := response.Body()
internalError.ErrorBody(rawBody)
if internalError.MeilisearchApiError.Code == "" {
return internalError.WithErrCode(MeilisearchApiErrorWithoutMessage)
}
return internalError.WithErrCode(MeilisearchApiError)
}
return nil
}
func (c *Client) handleResponse(req *internalRequest, response *fasthttp.Response, internalError *Error) (err error) {
if req.withResponse != nil {
// A json response is mandatory, so the response interface{} need to be unmarshal from the response payload.
rawBody := response.Body()
internalError.ResponseToString = string(rawBody)
var err error
if resp, ok := req.withResponse.(json.Unmarshaler); ok {
err = resp.UnmarshalJSON(rawBody)
req.withResponse = resp
} else {
err = json.Unmarshal(rawBody, req.withResponse)
}
if err != nil {
return internalError.WithErrCode(ErrCodeResponseUnmarshalBody, err)
}
}
return nil
}