Skip to content

Commit

Permalink
instead of marshaling to JSON and then into a buffer, just use a buff…
Browse files Browse the repository at this point in the history
…er when building the request body
  • Loading branch information
austin-denoble committed Jun 17, 2024
1 parent 05f0851 commit cf5c097
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 11 deletions.
18 changes: 8 additions & 10 deletions internal/pkg/utils/network/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,19 +100,18 @@ func decodeResponse[T any](resp *http.Response, target *T) error {
func RequestWithBody[B any](baseUrl string, path string, method string, body B) (*http.Response, error) {
url := baseUrl + path

var bodyJson []byte
bodyJson, err := json.Marshal(body)
var buf bytes.Buffer
err := json.NewEncoder(&buf).Encode(body)
if err != nil {
log.Error().
Err(err).
Str("method", method).
Str("url", url).
Msg("Error marshalling JSON")
Msg("Error encoding body")
return nil, pcio.Errorf("error marshalling JSON: %v", err)
}
bodyBuffer := bytes.NewBuffer(bodyJson)

req, err := buildRequest(method, url, bodyBuffer)
req, err := buildRequest(method, url, &buf)
log.Info().
Str("method", method).
Str("url", url).
Expand Down Expand Up @@ -140,19 +139,18 @@ func RequestWithBody[B any](baseUrl string, path string, method string, body B)
func RequestWithBodyAndDecode[B any, R any](baseUrl string, path string, method string, body B) (*R, error) {
url := baseUrl + path

var bodyJson []byte
bodyJson, err := json.Marshal(body)
var buf bytes.Buffer
err := json.NewEncoder(&buf).Encode(body)
if err != nil {
log.Error().
Err(err).
Str("method", method).
Str("url", url).
Msg("Error marshalling JSON")
Msg("Error encoding body")
return nil, pcio.Errorf("error marshalling JSON: %v", err)
}
bodyBuffer := bytes.NewBuffer(bodyJson)

req, err := buildRequest(method, url, bodyBuffer)
req, err := buildRequest(method, url, &buf)
log.Info().
Str("method", method).
Str("url", url).
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/utils/network/request_post.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,12 @@ func PostMultipartFormDataAndDecode[R any](baseUrl string, path string, bodyPath
return nil, pcio.Errorf("error closing writer: %v", err)
}

// Override Content-Type to support multipart/form-data
req, err := buildRequest(http.MethodPost, url, &requestBody)
if err != nil {
return nil, pcio.Errorf("error building request: %v", err)
}

// Override Content-Type to support multipart/form-data
req.Header.Set("Content-Type", writer.FormDataContentType())

log.Info().
Expand Down

0 comments on commit cf5c097

Please sign in to comment.