Skip to content

Commit

Permalink
S-108582 Improve error handling and redirection
Browse files Browse the repository at this point in the history
  • Loading branch information
jberta-agency04 committed May 2, 2024
1 parent 5e00a85 commit 077c4bd
Showing 1 changed file with 29 additions and 16 deletions.
45 changes: 29 additions & 16 deletions http/http_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,24 +110,12 @@ func (httpClient *HttpClient) sendRequest(ctx context.Context, method string, pa
})
}

// sendRequestWithCustomHeaders sends an HTTP request with a custom configuration and headers.
// sendRequestWithCustomHeaders sends an HTTP request with a custom configuration and headers, returns HTTP response body.
func (httpClient *HttpClient) sendRequestWithCustomHeaders(ctx context.Context, config *RequestConfig) ([]byte, error) {
client := httpClient.client
if client == nil {
return nil, fmt.Errorf("http client is uninitialized")
}
theUrl := httpClient.createUrl(config.Path, config.QueryParams...)
req, err := http.NewRequestWithContext(ctx, config.method, theUrl, bytes.NewBuffer(config.Body))
resp, err := httpClient.doSendHttpRequest(ctx, config)
if err != nil {
return nil, err
}
setHeaders(req, httpClient.headers)
setHeaders(req, config.Headers)

resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("%s error: %v", config.method, err)
}

defer func(Body io.ReadCloser) {
if deferredErr := Body.Close(); deferredErr != nil {
Expand All @@ -140,14 +128,39 @@ func (httpClient *HttpClient) sendRequestWithCustomHeaders(ctx context.Context,
return nil, fmt.Errorf("read body error: %v", err)
}

//TODO: handle 3xx statuses
if resp.StatusCode >= 299 {
if resp.StatusCode >= 300 && resp.StatusCode < 400 {
return nil, fmt.Errorf("%v redirect status: use sendHttpRequest instead to handle redirection", resp.StatusCode)
}

if resp.StatusCode >= 400 {
return data, fmt.Errorf("%v - %s", resp.StatusCode, string(data[:]))
}

return data, err
}

// doSendHttpRequest sends an HTTP request with a custom configuration and headers, returns whole HTTP response.
func (httpClient *HttpClient) doSendHttpRequest(ctx context.Context, config *RequestConfig) (*http.Response, error) {
client := httpClient.client
if client == nil {
return nil, fmt.Errorf("http client is uninitialized")
}
theUrl := httpClient.createUrl(config.Path, config.QueryParams...)
req, err := http.NewRequestWithContext(ctx, config.method, theUrl, bytes.NewBuffer(config.Body))
if err != nil {
return nil, err
}
setHeaders(req, httpClient.headers)
setHeaders(req, config.Headers)

resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("%s error: %v", config.method, err)
}

return resp, nil
}

// setHeaders sets the headers of an HTTP request based on the provided map of headers.
func setHeaders(request *http.Request, headers map[string][]string) {
if headers != nil {
Expand Down

0 comments on commit 077c4bd

Please sign in to comment.