2

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.

6
  • not sure, but, when you walk the dirs, aren't you attempting to delete the parents first? You may want to delete the deepest files/dirs first, then the parents. Commented Sep 23, 2016 at 11:31
  • 1
    See: stackoverflow.com/questions/33450980/… Commented Sep 23, 2016 at 11:39
  • @Jean-FrançoisFabre I updated function "deletefile", to except the parents.But does not work. Commented Sep 23, 2016 at 11:40
  • @Amd thanks ! It work to me. Commented Sep 23, 2016 at 11:56
  • 1
    the defer is unnecessary in your exit handlerfunc Commented Sep 23, 2016 at 20:00

1 Answer 1

6

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).
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.