-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathrequest.go
More file actions
94 lines (78 loc) · 1.84 KB
/
request.go
File metadata and controls
94 lines (78 loc) · 1.84 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package directusapi
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httputil"
"net/url"
"reflect"
)
const tagName = "json"
type request struct {
ctx context.Context
method string
url string
qv map[string]string
body any
}
func (a *API[R, W, PK]) executeRequest(r request, expectedStatus int, dest any) error {
if dest != nil && reflect.ValueOf(dest).Kind() != reflect.Ptr {
return fmt.Errorf("dest has to be a pointer")
}
var b io.Reader
if r.body != nil {
bodyBytes, err := json.Marshal(r.body)
if err != nil {
return fmt.Errorf("marshal request body: %w", err)
}
b = bytes.NewBuffer(bodyBytes)
}
req, err := http.NewRequestWithContext(
r.ctx,
r.method,
r.url,
b,
)
if err != nil {
return fmt.Errorf("create request: %w", err)
}
queryValues := url.Values{}
for k, v := range r.qv {
queryValues.Set(k, v)
}
req.URL.RawQuery = queryValues.Encode()
req.Header.Set("Authorization", "Bearer "+a.BearerToken)
req.Header.Set("Content-Type", "application/json")
if a.debug {
reqDump, _ := httputil.DumpRequestOut(req, true)
fmt.Println("--- Request start ---")
fmt.Println(string(reqDump))
fmt.Println("--- Request end ---")
}
resp, err := a.HTTPClient.Do(req)
if err != nil {
return fmt.Errorf("execute request: %v", err)
}
defer resp.Body.Close()
if a.debug {
respDump, _ := httputil.DumpResponse(resp, true)
fmt.Println("--- Response start ---")
fmt.Println(string(respDump))
fmt.Println("--- Response end ---")
}
if resp.StatusCode != expectedStatus {
respBytes, _ := ioutil.ReadAll(resp.Body)
return fmt.Errorf("unexpected status %s: %s", resp.Status, string(respBytes))
}
if dest != nil {
err = json.NewDecoder(resp.Body).Decode(dest)
if err != nil {
return fmt.Errorf("decoding json response: %w", err)
}
}
return nil
}