One approach that I use is to make new invocations of the program try to 
clean up after older ones.  For example, if you name your temp directories 
with a particular pattern, you can delete old directories on start up. 
 Ideally you _should_ try to clean up in the same process, but it isn't 
always possible.  Even cleaning up 99.99% of the time is still not 100%. 
 What I do is something like:

tmp := filepath.join(os.Tempdir(), "mydir")
os.RemoveAll(tmp) 
t, err := ioutil.TempFile(tmp, "prefix")
if err != nil {
  // ...
}
defer os.Remove(t.Name())
defer t.Close()



Some random other thoughts about temp files:

1.  If you are running on Windows, you have to make sure to close all 
references to the file before you can delete it.  
2.  If you press Ctrl-C in the middle of your program (or it terminates 
abnormally), none of the defers will be run.  You can try to catch this, 
but its kind of moot, since the signal handler is usually not in the same 
scope as the file access.

On Monday, November 21, 2016 at 9:08:03 AM UTC-8, Ondrej wrote:
>
> I already noted that in my very first post, "How do I clean up? As I said, 
> the app does not persist (so I can't defer os.Remove)"
>
> I guess I wasn't quite clear about my intentions, so never mind, I'll just 
> handle it somehow. 
>
> Thanks all for your suggestions.
>
> On Monday, 21 November 2016 16:57:56 UTC, Val wrote:
>>
>> OK, I had overlooked the fact that cleanup is important to you, which 
>> makes sense for security and to save disk space early.
>> TempFile, TempDir don't do the cleanup, but the OS will sooner or later.
>> Here is my new suggestion for a file 
>> <http://www.programming-idioms.org/idiom/138/create-temp-file/1751/go> 
>> and for a dir 
>> <http://www.programming-idioms.org/idiom/139/create-temp-directory/1757/go> 
>> :
>>
>> tmpfile, err := ioutil.TempFile("", "")
>> checkerr(err)
>> defer os.Remove(tmpfile.Name())
>>
>>
>> dir, err := ioutil.TempDir("", "")
>> checkerr(err)
>> defer os.RemoveAll(dir)
>>
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to