Skip to content

Commit

Permalink
[req] Guess the value of the 'Content-Type' header based on the reque…
Browse files Browse the repository at this point in the history
…st body type
  • Loading branch information
andyone committed Oct 10, 2024
1 parent e3fcfd7 commit 43aee19
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 13 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
## Changelog

### [13.6.1](https://kaos.sh/ek/13.6.1)

- `[req]` Guess the value of the `Content-Type` header based on the request body type

### [13.6.0](https://kaos.sh/ek/13.6.0)

- `[setup]` Added package to install/uninstall application as a service
Expand Down
28 changes: 16 additions & 12 deletions req/req.go
Original file line number Diff line number Diff line change
Expand Up @@ -590,12 +590,16 @@ func (e *Engine) doRequest(r Request, method string) (*Response, error) {
r.URL += "?" + r.Query.Encode()
}

bodyReader, err := getBodyReader(r.Body)
bodyReader, contentType, err := getBodyReader(r.Body)

if err != nil {
return nil, RequestError{ERROR_BODY_ENCODE, err.Error()}
}

if r.ContentType == "" {
r.ContentType = contentType
}

req, err := createRequest(e, r, bodyReader)

if err != nil {
Expand Down Expand Up @@ -736,25 +740,25 @@ func createFormFile(w *multipart.Writer, fieldName, file string) (io.Writer, err
return w.CreateFormFile(fieldName, filepath.Base(file))
}

func getBodyReader(body any) (io.Reader, error) {
func getBodyReader(body any) (io.Reader, string, error) {
switch u := body.(type) {
case nil:
return nil, nil
return nil, "", nil
case string:
return strings.NewReader(u), nil
return strings.NewReader(u), CONTENT_TYPE_PLAIN, nil
case io.Reader:
return u, nil
return u, CONTENT_TYPE_OCTET_STREAM, nil
case []byte:
return bytes.NewReader(u), nil
default:
jsonBody, err := json.MarshalIndent(body, "", " ")
return bytes.NewReader(u), CONTENT_TYPE_OCTET_STREAM, nil
}

if err == nil {
return bytes.NewReader(jsonBody), nil
}
jsonBody, err := json.MarshalIndent(body, "", " ")

return nil, err
if err == nil {
return bytes.NewReader(jsonBody), CONTENT_TYPE_JSON, nil
}

return nil, "", err
}

func isURL(url string) bool {
Expand Down
2 changes: 1 addition & 1 deletion version.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ package ek
// ////////////////////////////////////////////////////////////////////////////////// //

// VERSION is current ek package version
const VERSION = "13.6.0"
const VERSION = "13.6.1"

0 comments on commit 43aee19

Please sign in to comment.