我制作了一个命令行应用程序,在其中我正在压缩文件夹并在本地服务器上进行共享,以供其他人下载.我要做的是在关闭服务器后立即删除压缩文件夹的副本.这是我的代码:
func main() {
//flag to specify whether we will be uploading folder or a single file
zipped := flag.Bool("z",false,"Use for zipping folders and serving them as a single file on the server.(Deletes the zipped file once the server closes.)")
save := flag.Bool("s",false,"Use with -z for saving the zipped files locally even after the server closes.")
flag.Parse()
if len(flag.Args())>0{
if *zipped{
fmt.Println("zipping...")
flag.Args()[0]=ZipFile()
if !(*save){
//I expect this to remove the file when I hit ctrl+c on cmd
defer os.Remove(flag.Args()[0])
}
}
http.HandleFunc("/",ShareFile)
fmt.Printf("Sharing file on %s:8080\n",GetOutboundIP())
log.Fatal(http.ListenAndServe(":8080",nil))
}else{
fmt.Println("Invalid usage. No file mentioned. Use wshare -h for help.")
}
}
当我按下ctrl-c键时,程序退出,主功能关闭,因此不应该运行os.删除(xyz)是否执行?A tour of go表示,当函数返回时,defer执行表达式.在这里,我觉得梅因根本没有机会归还任何东西.
要实现我想要做的事情,解决办法是什么?我脑子里有一些解决方案,比如等待按键等等,但我希望这个程序超级简单,那么有没有一种方法可以在服务器关闭/程序退出时立即删除文件,而不需要我进一步输入呢?