forked from magnusbaeck/logstash-filter-verifier
/
deleted_tempfile.go
42 lines (37 loc) · 1.15 KB
/
deleted_tempfile.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Copyright (c) 2015-2016 Magnus Bäck <magnus@noun.se>
package logstash
import (
"io/ioutil"
"os"
)
// deletedTempFile acts like a regular file (by embedding os.File) but
// deletes the file when the file is closed.
type deletedTempFile struct {
*os.File
}
// NewDeletedTempFile creates a new temporary file that will be
// deleted upon closing. It uses the TempFile function from io/ioutil
// for the creation of the file and the dir and prefix parameters are
// passed straight through.
func newDeletedTempFile(dir, prefix string) (*deletedTempFile, error) {
f, err := ioutil.TempFile(dir, prefix)
if err != nil {
return nil, err
}
return &deletedTempFile{f}, nil
}
// Close closes the underlying file and deletes it. The deletion will
// still take place even if the file closing fails but the error
// returned will be the one returned from the call to the Close method
// of the embedded os.File.
func (f *deletedTempFile) Close() error {
closeErr := f.File.Close()
removeErr := os.Remove(f.Name())
if closeErr != nil {
return closeErr
}
if removeErr != nil {
log.Error("Problem deleting temporary file: %s", removeErr.Error())
}
return nil
}