Skip to content

Data: handle any type gracefully based on "Content-Type" of headers #48

@wenchy

Description

@wenchy

requests/request.go

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:

  1. 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...
  1. 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions