-
Notifications
You must be signed in to change notification settings - Fork 499
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Split module in client and requests. Add unit tests
- Loading branch information
1 parent
525079f
commit a28db13
Showing
7 changed files
with
380 additions
and
100 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,98 +1,85 @@ | ||
package apiclient | ||
|
||
import ( | ||
"encoding/base64" | ||
"encoding/json" | ||
"fmt" | ||
"io/ioutil" | ||
"net/http" | ||
"net/url" | ||
"time" | ||
|
||
"github.com/pkg/errors" | ||
) | ||
|
||
func (c *APIClient) createRequestBody(endpoint string, queryParams url.Values) (*http.Request, error) { | ||
fullURL := c.url(endpoint, queryParams) | ||
req, err := http.NewRequest("GET", fullURL, nil) | ||
if err != nil { | ||
return nil, errors.Wrap(err, "http GET request creation failed") | ||
} | ||
return req, nil | ||
const ( | ||
maxRetries = 5 | ||
initialBackoff = 1 * time.Second | ||
) | ||
|
||
func isRetryableStatusCode(statusCode int) bool { | ||
return statusCode == http.StatusTooManyRequests || statusCode == http.StatusServiceUnavailable | ||
} | ||
|
||
func (c *APIClient) callAPI(req *http.Request) (interface{}, error) { | ||
client := c.HTTP | ||
if client == nil { | ||
client = &http.Client{} | ||
} | ||
func (c *APIClient) GetURL(endpoint string, qstr url.Values) string { | ||
return fmt.Sprintf("%s/%s?%s", c.BaseURL, endpoint, qstr.Encode()) | ||
} | ||
|
||
resp, err := client.Do(req) | ||
if err != nil { | ||
return nil, errors.Wrap(err, "http GET request failed") | ||
func (c *APIClient) CallAPI(reqParams RequestParams) (interface{}, error) { | ||
if reqParams.QueryParams == nil { | ||
reqParams.QueryParams = url.Values{} | ||
} | ||
defer resp.Body.Close() | ||
|
||
if resp.StatusCode != http.StatusOK { | ||
return nil, fmt.Errorf("API request failed with status %d", resp.StatusCode) | ||
if reqParams.Headers == nil { | ||
reqParams.Headers = map[string]interface{}{} | ||
} | ||
|
||
body, err := ioutil.ReadAll(resp.Body) | ||
url := c.GetURL(reqParams.Endpoint, reqParams.QueryParams) | ||
reqBody, err := CreateRequestBody(reqParams.RequestType, url) | ||
if err != nil { | ||
return nil, fmt.Errorf("failed to read response body: %w", err) | ||
return nil, errors.Wrap(err, "http request creation failed") | ||
} | ||
|
||
var result interface{} | ||
if err := json.Unmarshal(body, &result); err != nil { | ||
return nil, fmt.Errorf("failed to unmarshal JSON: %w", err) | ||
SetAuthHeaders(reqBody, c.authType, c.authHeaders) | ||
SetHeaders(reqBody, reqParams.Headers) | ||
client := c.HTTP | ||
if client == nil { | ||
client = &http.Client{} | ||
} | ||
|
||
return result, nil | ||
} | ||
|
||
func setHeaders(req *http.Request, args map[string]interface{}) { | ||
for key, value := range args { | ||
strValue, ok := value.(string) | ||
if !ok { | ||
fmt.Printf("Skipping non-string value for header %s\n", key) | ||
continue | ||
} | ||
|
||
req.Header.Set(key, strValue) | ||
} | ||
} | ||
var result interface{} | ||
retries := 0 | ||
|
||
func setAuthHeaders(req *http.Request, authType string, args map[string]interface{}) error { | ||
switch authType { | ||
case "basic": | ||
username, ok := args["username"].(string) | ||
if !ok { | ||
return fmt.Errorf("missing or invalid username") | ||
} | ||
password, ok := args["password"].(string) | ||
if !ok { | ||
return fmt.Errorf("missing or invalid password") | ||
for retries <= maxRetries { | ||
resp, err := client.Do(reqBody) | ||
if err != nil { | ||
return nil, errors.Wrap(err, "http request failed") | ||
} | ||
|
||
authHeader := "Basic " + base64.StdEncoding.EncodeToString([]byte(username+":"+password)) | ||
setHeaders(req, map[string]interface{}{ | ||
"Authorization": authHeader, | ||
}) | ||
|
||
case "api_key": | ||
apiKey, ok := args["api_key"].(string) | ||
if !ok { | ||
return fmt.Errorf("missing or invalid API key") | ||
defer resp.Body.Close() | ||
|
||
if resp.StatusCode == http.StatusOK { | ||
body, err := ioutil.ReadAll(resp.Body) | ||
if err != nil { | ||
return nil, fmt.Errorf("failed to read response body: %w", err) | ||
} | ||
|
||
if err := json.Unmarshal(body, &result); err != nil { | ||
return nil, fmt.Errorf("failed to unmarshal JSON: %w", err) | ||
} | ||
|
||
return result, nil | ||
} else if isRetryableStatusCode(resp.StatusCode) { | ||
retries++ | ||
backoffDuration := initialBackoff * time.Duration(1<<retries) | ||
if retries <= maxRetries { | ||
fmt.Printf("Received retryable status %d. Retrying in %v...\n", resp.StatusCode, backoffDuration) | ||
time.Sleep(backoffDuration) | ||
} else { | ||
return nil, fmt.Errorf("Maximum retries reached after receiving status %d", resp.StatusCode) | ||
} | ||
} else { | ||
return nil, fmt.Errorf("API request failed with status %d", resp.StatusCode) | ||
} | ||
setHeaders(req, map[string]interface{}{ | ||
"Authorization": apiKey, | ||
}) | ||
|
||
default: | ||
return fmt.Errorf("unsupported auth type: %s", authType) | ||
} | ||
return nil | ||
} | ||
|
||
func (c *APIClient) url(endpoint string, qstr url.Values) string { | ||
return fmt.Sprintf("%s/%s?%s", c.BaseURL, endpoint, qstr.Encode()) | ||
return nil, fmt.Errorf("API request failed after %d retries", retries) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.