dqp21271 2016-09-23 11:27
浏览 143
已采纳

为什么我的Go程序无法删除文件?

I wrote a Go program that listens to a http request:

server := http.Server{
    Addr:        "0.0.0.0:65534",
    Handler:     &MyHandler{},
    ReadTimeout: 10 * time.Second,
}
server.ListenAndServe()

I set browser request "/exit" mapping to a function:

func exit(w http.ResponseWriter, r *http.Request) {
    DeleteCache("../upload")
    defer os.Exit(0)
}

I want to delete the files inside folder "../upload", and my DeleteCache function looks like this:

func deletefile(path string, f os.FileInfo, err error) error {
    if path == "../upload" {
        return nil
    }
    err1 := os.Remove(path)
    if err1 != nil {
        log.Fatal(err1)
        return err1
    }
    return err1
}

func DeleteCache(dirName string) {
    err := filepath.Walk(dirName, deletefile)
    checkNil(err)
}

Next, I wrote test code like this:

func TestDeleteFile(t *testing.T) {
    //service is a package name.
    service.DeleteCache("../upload")
}

The test code can run very well, it deleted all of the files inside folder "../upload"

But when I ran the program fully, then opened browser access "0.0.0.0:65534/exit", the program tells me

remove ../upload: directory not empty

other URLs could run well, except "/exit" and it's handler function named "exit"

I guess the reason is conflict between the "go http listing service" and the "filepath.Walk", they can't run at the same time. Maybe I should run it use goroutines.

I would greatly appreciate a reply.

  • 写回答

1条回答 默认 最新

  • drdyszuy488152 2016-09-23 11:57
    关注

    You may use os.RemoveAll("../upload"):

    func RemoveAll(path string) error 
    
    // RemoveAll removes path and any children it contains.
    // It removes everything it can but returns the first error
    // it encounters. If the path does not exist, RemoveAll
    // returns nil (no error).
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大