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","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时,程序退出并且main函数关闭,因此,不应该执行os.Remove(xyz)吗? A tour of go说,defer在函数返回时执行表达式.在这里,我觉得主要没有得到任何回报的机会.
什么是解决方法来实现我想要做的事情?我有一些解决方案,比如等待按键等,但我希望这个程序非常简单,所以有没有办法在服务器关闭/程序退出时立即删除文件而不需要我的任何进一步输入?