张海宁
张海宁

Reputation: 21

Does the file need to be closed?

Using golang gin, I read file data using:

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

Do I need to write this?

defer file.Close()

I jump to the source code, it says:

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

If it uses os.Open, I guess I must close the file, but if it retuns the sectionReadCloser{r}, the Close function shows like this:

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

The close function of seciontReadCloser doesn't do anything. And I find that it does return the sectionReadCloser{r}. I guess I should close the file, but I still want to know when it will return the os.Open. I will keep going to read the source code and try to understand it. It would be nice if someone gives me some advice.

Upvotes: 1

Views: 2251

Answers (1)

Adrian
Adrian

Reputation: 46532

If the file returned implements io.Closer (i.e., if it has a Close method), assume you are responsible for closing it unless the documentation explicitly states otherwise.

Upvotes: 6

Related Questions