[bugfix] close files before error return (#3163)

* close files before error return

* use defer statements

* shuffle around some defers
This commit is contained in:
kim 2024-08-02 14:11:24 +00:00 committed by GitHub
parent 0f734a2410
commit e5e996b28a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 9 additions and 9 deletions

View file

@ -75,12 +75,14 @@ func terminateExif(outpath, inpath string, ext string) error {
if err != nil { if err != nil {
return gtserror.Newf("error opening input file %s: %w", inpath, err) return gtserror.Newf("error opening input file %s: %w", inpath, err)
} }
defer inFile.Close()
// Open output file at given path. // Open output file at given path.
outFile, err := os.Create(outpath) outFile, err := os.Create(outpath)
if err != nil { if err != nil {
return gtserror.Newf("error opening output file %s: %w", outpath, err) return gtserror.Newf("error opening output file %s: %w", outpath, err)
} }
defer outFile.Close()
// Terminate EXIF data from 'inFile' -> 'outFile'. // Terminate EXIF data from 'inFile' -> 'outFile'.
err = terminator.TerminateInto(outFile, inFile, ext) err = terminator.TerminateInto(outFile, inFile, ext)
@ -88,9 +90,5 @@ func terminateExif(outpath, inpath string, ext string) error {
return gtserror.Newf("error terminating exif data: %w", err) return gtserror.Newf("error terminating exif data: %w", err)
} }
// Done with files.
_ = inFile.Close()
_ = outFile.Close()
return nil return nil
} }

View file

@ -120,15 +120,17 @@ func getMimeType(ext string) string {
// chance that Linux's sendfile syscall can be utilised for optimal // chance that Linux's sendfile syscall can be utilised for optimal
// draining of data source to temporary file storage. // draining of data source to temporary file storage.
func drainToTmp(rc io.ReadCloser) (string, error) { func drainToTmp(rc io.ReadCloser) (string, error) {
tmp, err := os.CreateTemp(os.TempDir(), "gotosocial-*") defer rc.Close()
// Open new temporary file.
tmp, err := os.CreateTemp(
os.TempDir(),
"gotosocial-*",
)
if err != nil { if err != nil {
return "", err return "", err
} }
// Close readers
// on func return.
defer tmp.Close() defer tmp.Close()
defer rc.Close()
// Extract file path. // Extract file path.
path := tmp.Name() path := tmp.Name()