Add context timeouts for third-party requests
Some checks failed
/ golint (push) Failing after 3m56s

Avoid hanging a goroutine for a long time.
This commit is contained in:
Eli Ribble 2026-05-19 00:24:16 +00:00
parent 2093ea74c4
commit 15d8966971
No known key found for this signature in database
11 changed files with 80 additions and 5 deletions

View file

@ -2,6 +2,7 @@ package labelstudio
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
@ -35,6 +36,9 @@ var ACCESS_TOKEN_DURATION_SECONDS time.Duration = 240 * time.Second
// GetAccessToken converts the API key into an access token
func (c *Client) GetAccessToken() error {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
// Create request body
reqBody := map[string]string{
"refresh": c.APIKey,
@ -47,7 +51,7 @@ func (c *Client) GetAccessToken() error {
}
// Create request
req, err := http.NewRequest("POST", fmt.Sprintf("%s/api/token/refresh", c.BaseURL), bytes.NewBuffer(jsonBody))
req, err := http.NewRequestWithContext(ctx, "POST", fmt.Sprintf("%s/api/token/refresh", c.BaseURL), bytes.NewBuffer(jsonBody))
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
@ -91,6 +95,9 @@ func (c *Client) GetAccessToken() error {
}
func (c *Client) makeRequest(method string, path string, payload []byte) (*http.Response, error) {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
// Check if we have an access token, if not try to get it
if c.AccessToken == "" || time.Now().After(c.AccessTokenExpires) {
if err := c.GetAccessToken(); err != nil {
@ -99,7 +106,7 @@ func (c *Client) makeRequest(method string, path string, payload []byte) (*http.
}
// Create request
url := fmt.Sprintf("%s/%s", c.BaseURL, path)
req, err := http.NewRequest(method, url, bytes.NewBuffer(payload))
req, err := http.NewRequestWithContext(ctx, method, url, bytes.NewBuffer(payload))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}