Skip to content

Close files opened for string reads and MIME detection - #330

Merged
inhere merged 1 commit into
gookit:masterfrom
Muneer320:fix/close-owned-string-reader
Nov 29, 2026
Merged

inhere merged 1 commit into
gookit:masterfrom
Muneer320:fix/close-owned-string-reader

Conversation

@Muneer320

Copy link
Copy Markdown
Contributor

fsutil.ReadStringOrErr(path) and fsutil.MimeType(path) open files but return without closing them. On Windows, an immediate os.Remove(path) can then fail with a sharing violation even though the read succeeded. On Linux, the descriptor remains open after the call until garbage collection can reclaim the file.

Defer closing the files these eager readers open. This also covers MIME detection through the DetectMime alias and IsImageFile. Caller-provided readers, including *os.File, retain their existing ownership behavior.

Public API reproduction on Windows:

f, err := os.CreateTemp("", "read-string-*.txt")
if err != nil { panic(err) }
path := f.Name()
if _, err := f.WriteString("sample contents"); err != nil { panic(err) }
if err := f.Close(); err != nil { panic(err) }
text, readErr := fsutil.ReadStringOrErr(path)
fmt.Println(text, readErr)
fmt.Println(os.Remove(path))

Before the fix, the read returns sample contents and no error, but removal fails. With the fix, removal succeeds.

Validation on Go 1.19/Linux and current Go/Linux and Windows:

  • Public before/after reproductions for ReadStringOrErr, MimeType and DetectMime, including Linux descriptor counts.
  • Fifteen public ownership/error controls, including caller-provided files that remain usable after string reads and MIME detection. A deliberately incorrect change that also closes borrowed files is rejected by these controls.
  • Full native coverage suite and go vet ./fsutil; full race suite on current Go/Linux.

ReadOrErr and the scanner factories keep their existing behavior.

@inhere
inhere merged commit 1ddb003 into gookit:master Nov 29, 2026
17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants