未调用golang纤程延迟os.remove()

x8diyxa7  于 2023-03-06  发布在  Go
关注(0)|答案(1)|浏览(118)

在我的golang项目中,我需要删除一个用户下载的文件,我使用了defer,但是下载后没有调用它,所以文件没有被删除,代码如下:

func (h *Handler) Download(c *fiber.Ctx) error {
    filename := c.Query("filename")
    c.Attachment(filename)
    tempFile := filepath.Join(os.TempDir(), filename)

    //Open the file for reading
    file, err := os.Open(tempFile)
    if err != nil {
        return err
    }
    //delete the file when everything is done, not working
    defer os.Remove(tempFile)
    
    //read the file
    b, err := ioutil.ReadAll(file)
    if err != nil {
        return er.Wrap(err)
    }

    //close the file explicitly after reading
    err = file.Close()
    if err != nil {
        return er.Wrap(err)
    }

    //also I tried to delete the file explicitly but keep getting error saying that the file is being used by another process
    //os.Remove(tempFile)
    //send the file to user
    return c.Send(b)
}

有什么好办法都欢迎。谢谢。

xu3bshqb

xu3bshqb1#

mybe os.Remove返回错误,例如,tempFile的路径为错误
使用以下代码查看错误

defer func() {
        err := os.Remove(tempFile)
        if err != nil {
            fmt.Printf("%v\n", err)
        }
    }()

相关问题