Home > Mobile >  `no such file or directory` with `os.Remove` inside go routine
`no such file or directory` with `os.Remove` inside go routine

Time:05-24

I added a new command to my CLI application using the Cobra framework. This command is supposed to start a TCP server that accepts socket connections. It receives a payload which is an absolute path to a file/directory and tries to delete it. Here is the code for the command

package cmd

import (
    "bufio"
    "fmt"
    "net"
    "os"

    "github.com/spf13/cobra"
    "wpgenius.io/util"
)

var cachePurgerCmd = &cobra.Command{
    Use:   "cache-purger",
    Short: "Listen for request to purge NGINX page cache",
    Run: func(cmd *cobra.Command, args []string) {
        dstream, err := net.Listen("tcp", ":9876")

        if err != nil {
            util.HandleError(err, "Can not start listener..")
            return
        }

        fmt.Println("Listening for purge requests...")

        defer dstream.Close()

        for {
            con, err := dstream.Accept()

            if err != nil {
                util.HandleError(err, "Can not accept connection")
                os.Exit(1)
            }

            go handleRequest(con)
        }
    },
}

func handleRequest(con net.Conn) {
    path, err := bufio.NewReader(con).ReadString('\n')

    if err != nil {
        return
    }

    defer con.Close()

    err = os.Remove(path)

    if err != nil {
        con.Write([]byte("ERROR"))
        fmt.Println(err)
        util.HandleError(err, "Can not delete cache file")
        return
    }

    con.Write([]byte("SUCCESS"))
}

func init() {
    rootCmd.AddCommand(cachePurgerCmd)
}

Although the file/directory exists, I still get no such file or directory error. I did a sanity check by simply adding the os.Remove to the main function to make sure it's not related to the path and I can see it successfully delete the file/directory.

I'm not sure if it has something to do with go routing or with the tcp server!

Any help will be highly appreciated!

CodePudding user response:

I guess the point is \n in the path you input.

  • Related