golang fiber defer os.Remove()未被调用

huangapple go评论64阅读模式
英文:

golang fiber defer os.Remove() not called

问题

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

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

    // 打开文件进行读取
    file, err := os.Open(tempFile)
    if err != nil {
        return err
    }
    // 在所有操作完成后删除文件,但是不起作用
    defer os.Remove(tempFile)
    
    // 读取文件内容
    b, err := ioutil.ReadAll(file)
    if err != nil {
        return er.Wrap(err)
    }

    // 读取完成后显式关闭文件
    err = file.Close()
    if err != nil {
        return er.Wrap(err)
    }

    // 我也尝试了显式删除文件,但是一直收到文件正在被另一个进程使用的错误
    // os.Remove(tempFile)
    // 将文件发送给用户
    return c.Send(b)
}

有什么想法可以解决这个问题吗?谢谢。

英文:

In my golang project I need to delete a file once it has been downloaded by user. I use defer but it is not called after download so the file is not deleted. The code is as follows:

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

Any ideas how to fix it would be welcome. Thank you.

答案1

得分: 2

也许os.Remove返回一个错误,例如,tempFile的路径错误。

使用以下代码查看错误:

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

请注意,这是一个示例代码,用于演示如何处理os.Remove可能返回的错误。

英文:

mybe os.Remove return a error,eg. tempFile's path is error

use follow code to see the error

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

huangapple
  • 本文由 发表于 2023年3月1日 17:16:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75601625.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定