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.