-
Notifications
You must be signed in to change notification settings - Fork 1
Open
Labels
enhancementNew feature or requestNew feature or request
Description
Lines 80 to 95 in cbe3a6b
| // requestData sends an HTTP request to the specified URL, with raw string | |
| // as the request body. | |
| func requestData(c *Client, method, url string, opts *Options) (*Response, error) { | |
| body := bytes.NewBuffer(nil) | |
| if opts.Data != nil { | |
| d := fmt.Sprintf("%v", opts.Data) | |
| _, err := body.WriteString(d) | |
| if err != nil { | |
| return nil, err | |
| } | |
| } | |
| // TODO: judge content type | |
| // opts.Headers["Content-Type"] = "application/x-www-form-urlencoded" | |
| opts.Body = body | |
| return c.request(method, url, opts, body.Bytes()) | |
| } |
Problem
r, err := requests.Post("http://example.com",
requests.Data(`{"group":1,"version":"v1.0"`))
if err != nil {
// ...
}vs
r, err := requests.Post("http://example.com",
requests.Data([]byte(`{"group":1,"version":"v1.0"`)))
if err != nil {
// ...
}The underlying d := fmt.Sprintf("%v", opts.Data) is a problem. We should firstly decide the data type based on "Content-Type" of headers. Refer to https://github.com/go-resty/resty/blob/v3/middleware.go#L414
For examples:
- The user specifies "Content-Type" explicitly, then
- "application/x-www-form-urlencoded" or "text/plain": treat data as string
d := fmt.Sprintf("%s", opts.Data) - "application/octet-stream": treat data as bytes
d := fmt.Sprintf("%v", opts.Data) - more content types...
- Other, if user does not specify "Content-Type" explicitly, then assert type swich on the data type
string[]byte- ...
Test
Keep sure the following two cases are the same HTTP request.
r, err := requests.Post("http://example.com",
requests.Data(`{"group":1,"version":"v1.0"`))
if err != nil {
// ...
}vs
r, err := requests.Post("http://example.com",
requests.Data([]byte(`{"group":1,"version":"v1.0"`)))
if err != nil {
// ...
}References
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
enhancementNew feature or requestNew feature or request