fix: use context in http calls

This commit is contained in:
Carlos Alexandro Becker 2025-06-30 08:38:18 -03:00
commit 7ec9d79229
No known key found for this signature in database
5 changed files with 47 additions and 25 deletions

View file

@ -1,6 +1,7 @@
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
@ -11,7 +12,7 @@ import (
)
// findGitHubREADME tries to find the correct README filename in a repository using GitHub API.
func findGitHubREADME(u *url.URL) (*source, error) {
func findGitHubREADME(ctx context.Context, u *url.URL) (*source, error) {
owner, repo, ok := strings.Cut(strings.TrimPrefix(u.Path, "/"), "/")
if !ok {
return nil, fmt.Errorf("invalid url: %s", u.String())
@ -23,12 +24,15 @@ func findGitHubREADME(u *url.URL) (*source, error) {
apiURL := fmt.Sprintf("https://api.%s/repos/%s/%s/readme", u.Hostname(), owner, repo)
//nolint:bodyclose
// it is closed on the caller
res, err := http.Get(apiURL) //nolint: gosec,noctx
req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiURL, nil)
if err != nil {
return nil, fmt.Errorf("unable to create request: %w", err)
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("unable to get url: %w", err)
}
defer res.Body.Close() //nolint:errcheck
body, err := io.ReadAll(res.Body)
if err != nil {
@ -41,9 +45,12 @@ func findGitHubREADME(u *url.URL) (*source, error) {
}
if res.StatusCode == http.StatusOK {
//nolint:bodyclose
// it is closed on the caller
resp, err := http.Get(result.DownloadURL) //nolint: noctx
// consumer of the source is responsible for closing the ReadCloser.
req, err := http.NewRequestWithContext(ctx, http.MethodGet, result.DownloadURL, nil)
if err != nil {
return nil, fmt.Errorf("unable to create request: %w", err)
}
resp, err := http.DefaultClient.Do(req) //nolint:bodyclose
if err != nil {
return nil, fmt.Errorf("unable to get url: %w", err)
}