-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.go
More file actions
201 lines (166 loc) · 7.09 KB
/
core.go
File metadata and controls
201 lines (166 loc) · 7.09 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
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
package httpx
import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/url"
"strings"
)
// do is the internal request executor used by all HTTP verb methods.
//
// It applies global headers, merges per-request overrides, encodes the request
// body based on Content-Type, appends query parameters, and finally executes the
// HTTP request using the underlying *http.Client.
//
// This method is not exposed publicly; the public API consists of Get, Post,
// Put, Patch, and Delete.
func (c *client) do(method, uri string, o *RequestOptions) (*http.Response, error) {
//────────────────────────────────────────────────────────────
// Merge global headers with per-request headers
//────────────────────────────────────────────────────────────
requestHeaders := make(http.Header)
// Apply global headers (from Config)
for key, values := range c.Headers {
if len(values) > 0 {
requestHeaders.Set(key, values[0])
}
}
// Override with per-request headers (from options)
if o.Headers != nil {
for key, values := range o.Headers {
if len(values) > 0 {
requestHeaders.Set(key, values[0])
}
}
}
//────────────────────────────────────────────────────────────
// Validate body usage
//────────────────────────────────────────────────────────────
if method == http.MethodGet && o.Body != nil {
return nil, fmt.Errorf("GET request cannot contain a body")
}
// Assign default Content-Type if a body exists but user didn't specify one.
if o.Body != nil && requestHeaders.Get("Content-Type") == "" {
requestHeaders.Set("Content-Type", "application/json")
}
// Determine base Content-Type (strip charset or options)
contentType := strings.ToLower(strings.Split(requestHeaders.Get("Content-Type"), ";")[0])
//────────────────────────────────────────────────────────────
// Encode request body
//────────────────────────────────────────────────────────────
var requestBody []byte
if o.Body != nil && method != http.MethodGet {
var err error
switch contentType {
// JSON ----------------------------------------------------
case "application/json":
requestBody, err = json.Marshal(o.Body)
// FORM URLENCODED -----------------------------------------
case "application/x-www-form-urlencoded":
values := url.Values{}
switch v := o.Body.(type) {
case map[string]string:
for k, val := range v {
values.Set(k, val)
}
case url.Values:
values = v
default:
return nil, fmt.Errorf("body must be map[string]string or url.Values for x-www-form-urlencoded")
}
requestBody = []byte(values.Encode())
// XML -----------------------------------------------------
case "application/xml", "text/xml":
requestBody, err = xml.Marshal(o.Body)
// MULTIPART FORM DATA -------------------------------------
case "multipart/form-data":
var b bytes.Buffer
writer := multipart.NewWriter(&b)
// Automatically set boundary in Content-Type
requestHeaders.Set("Content-Type", writer.FormDataContentType())
fields, ok := o.Body.(map[string]any)
if !ok {
return nil, fmt.Errorf("multipart/form-data requires body = map[string]any")
}
for key, val := range fields {
switch cast := val.(type) {
case []byte:
// file upload (raw bytes)
part, err := writer.CreateFormFile(key, key)
if err != nil {
return nil, err
}
if _, err := part.Write(cast); err != nil {
return nil, err
}
case string:
// form field value
if err := writer.WriteField(key, cast); err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("unsupported multipart field type %T for key %s", cast, key)
}
}
writer.Close()
requestBody = b.Bytes()
// PLAIN TEXT ----------------------------------------------
case "text/plain":
requestBody = []byte(fmt.Sprintf("%v", o.Body))
// RAW STREAM / BYTES --------------------------------------
case "application/octet-stream":
switch v := o.Body.(type) {
case []byte:
requestBody = v
case io.Reader:
requestBody, err = io.ReadAll(v)
default:
return nil, fmt.Errorf("octet-stream requires []byte or io.Reader body")
}
// DEFAULT → JSON ------------------------------------------
default:
requestBody, err = json.Marshal(o.Body)
}
if err != nil {
return nil, err
}
}
//────────────────────────────────────────────────────────────
// Wrap encoded body in an io.Reader
//────────────────────────────────────────────────────────────
var bodyReader io.Reader
if requestBody != nil {
bodyReader = bytes.NewBuffer(requestBody)
}
//────────────────────────────────────────────────────────────
// Append query parameters (?key=value)
//────────────────────────────────────────────────────────────
if o.Params != nil {
u, err := url.Parse(uri)
if err != nil {
return nil, err
}
q := u.Query()
for key, val := range o.Params {
q.Set(key, val)
}
u.RawQuery = q.Encode()
uri = u.String()
}
//────────────────────────────────────────────────────────────
// Construct the *http.Request
//────────────────────────────────────────────────────────────
req, err := http.NewRequest(method, uri, bodyReader)
if err != nil {
return nil, fmt.Errorf("unable to create request: %w", err)
}
req.Header = requestHeaders
//────────────────────────────────────────────────────────────
// Execute request using the underlying http.Client
//────────────────────────────────────────────────────────────
return c.httpClient.Do(req)
}