我制作了一个命令行应用程序,可以将文件夹压缩并共享到本地服务器上供他人下载。我想做的是,在关闭服务器时立即删除我的压缩文件夹副本。这是我的代码:
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.Remove(xyz)不应该被执行吗? A tour of go说,defer在函数返回时执行表达式。在这里,我感觉主函数根本没有机会返回任何东西。
有什么解决方法可以实现我想做的事情吗?我脑海中有一些解决方案,比如等待按键等,但我希望这个程序非常简单,所以有没有一种方法可以在服务器关闭/程序退出时立即删除文件,而无需我进一步输入?
main
函数被中断,因此您需要安装一个信号处理程序并在该函数内调用Remove
。 - squiguy