是否需要关闭文件?

张海宁*_*张海宁 0 gwt-gin file-upload go

当我使用golang杜松子酒时,请使用以下命令读取文件数据:

file, fileHeader, err:=ctx.Request.FormFile("blabla...")
Run Code Online (Sandbox Code Playgroud)

我需要写这些吗:

defer file.Close()
Run Code Online (Sandbox Code Playgroud)

我跳到源代码,它说:

// Open opens and returns the FileHeader's associated File.
func (fh *FileHeader) Open() (File, error) {
        if b := fh.content; b != nil {
                r := io.NewSectionReader(bytes.NewReader(b), 0, int64(len(b)))
                fmt.Printf("TODDLINE:152\n")
                fmt.Printf("TODDLINE:154:fmpfile:%#v\n", fh.tmpfile)
                fmt.Printf("TODDLINE:154:Filename:%#v\n", fh.Filename)
                return sectionReadCloser{r}, nil
        }
        fmt.Printf("TODDLINE:155\n")
        return os.Open(fh.tmpfile)
}
Run Code Online (Sandbox Code Playgroud)

如果使用os.Open,我想我必须关闭文件,但是如果重新调整sectionReadCloser {r},则Close函数显示如下:

func (rc sectionReadCloser) Close() error {
        return nil
}
Run Code Online (Sandbox Code Playgroud)

seciontReadCloser的关闭功能不执行任何操作。而且我发现它确实返回sectionReadCloser {r}。我想我应该关闭文件,但是我仍然想知道何时返回os.Open。我将继续阅读源代码并尝试理解它。如果有人给我一些建议会很好。

Adr*_*ian 6

如果file返回的实现io.Closer(即,如果具有Close方法),除非文档另有明确说明,否则假设您有责任关闭它。