Skip to content

Commit 5acb47c

Browse files
committed
fix: Improve error handling for Contents API response
Ensure response body is properly closed even when an error occurs by moving the defer statement before the error check. This prevents potential resource leaks when the Contents API returns an error with a non-nil response. Changes: - Move defer respContents.Body.Close() before error checking - Rename errContents to err for consistency - Add nil check for respContents before attempting to close body This follows Go best practices for handling HTTP responses and prevents potential goroutine/memory leaks.
1 parent bac36c1 commit 5acb47c

File tree

1 file changed

+5
-3
lines changed

1 file changed

+5
-3
lines changed

pkg/github/repositories.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -510,11 +510,13 @@ func GetFileContents(getClient GetClientFn, getRawClient raw.GetRawClientFn, t t
510510
// First, get file info from Contents API to retrieve SHA
511511
var fileSHA string
512512
opts := &github.RepositoryContentGetOptions{Ref: ref}
513-
fileContent, _, respContents, errContents := client.Repositories.GetContents(ctx, owner, repo, path, opts)
514-
if errContents == nil && respContents.StatusCode == http.StatusOK && fileContent != nil && fileContent.SHA != nil {
515-
fileSHA = *fileContent.SHA
513+
fileContent, _, respContents, err := client.Repositories.GetContents(ctx, owner, repo, path, opts)
514+
if respContents != nil {
516515
defer func() { _ = respContents.Body.Close() }()
517516
}
517+
if err == nil && respContents.StatusCode == http.StatusOK && fileContent != nil && fileContent.SHA != nil {
518+
fileSHA = *fileContent.SHA
519+
}
518520

519521
rawClient, err := getRawClient(ctx)
520522
if err != nil {

0 commit comments

Comments
 (0)