[英]`no such file or directory` with `os.Remove` inside go routine
I added a new command to my CLI application using the Cobra framework.我使用 Cobra 框架向我的 CLI 应用程序添加了一个新命令。 This command is supposed to start a TCP server that accepts socket connections.此命令应该启动接受套接字连接的 TCP 服务器。 It receives a payload which is an absolute
path to a file/directory and tries to delete it.它接收一个有效载荷,它是一个文件/目录的absolute
路径,并试图删除它。 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.尽管文件/目录存在,但我仍然no such file or directory
错误。 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.我通过简单地将os.Remove
添加到main
function 来进行完整性检查,以确保它与路径无关,并且我可以看到它成功删除了文件/目录。
I'm not sure if it has something to do with go routing
or with the tcp server
!我不确定它是否与go routing
或tcp server
有关!
Any help will be highly appreciated!任何帮助将不胜感激!
I guess the point is \n in the path you input.我想重点是您输入的路径中的 \n 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.