【问题标题】:Does the file need to be closed?文件需要关闭吗?
【发布时间】:2019-08-01 21:20:25
【问题描述】:

使用 golang gin,我使用以下方式读取文件数据:

file, fileHeader, err:=ctx.Request.FormFile("blabla...")

我需要写这个吗?

defer file.Close()

我跳转到源代码,上面写着:

// 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)
}

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

func (rc sectionReadCloser) Close() error {
        return nil
}

seciontReadCloser 的关闭函数没有任何作用。 我发现它确实返回了 sectionReadCloser{r}。 我想我应该关闭文件,但我仍然想知道它什么时候会返回 os.Open。我将继续阅读源代码并尝试理解它。如果有人给我一些建议,那就太好了。

【问题讨论】:

    标签: go file-upload go-gin


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2018-05-17
      • 1970-01-01
      • 2015-01-18
      • 2013-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-01
      • 1970-01-01
      相关资源
      最近更新 更多