-
Notifications
You must be signed in to change notification settings - Fork 2
/
securetemp.go
60 lines (51 loc) · 1.45 KB
/
securetemp.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package securetemp
import (
"io/ioutil"
"os"
)
// TODO(leon): It's {K,M,G}iB, not {K,M,G}B (with an "i")
const (
// SizeKB represents one Kibibyte
SizeKB = 1 << (10 * iota)
// SizeMB represents one Mebibyte (1024 KiB)
SizeMB
// SizeGB represents one Gibibyte (1024 MiB)
SizeGB
)
const (
// DefaultSize specifies the default size for a RAM disk in MB
DefaultSize = 4 * SizeMB
// globalPrefix will be used if we need a prefix for
// something (e.g. files & folders)
globalPrefix = "securetemp"
)
type CleanupFunc func()
// TempDir creates a new RAM disk with size 'size' (in bytes)
// and returns the path to it.
// Use this function only if you intend to create multiple
// files inside your RAM disk, else prefer to use 'TempFile'.
func TempDir(size int) (string, CleanupFunc, error) {
return createRAMDisk(size)
}
// TempFile creates a new RAM disk with size 'size' (in bytes),
// creates a temp file in it and returns a pointer to that file.
// Use this function only if you intend to create a single file
// inside your RAM disk, else prefer to use 'TempDir'.
func TempFile(size int) (*os.File, CleanupFunc, error) {
path, cleanupFunc, err := TempDir(size)
if err != nil {
return nil, nil, err
}
doCleanup := true
defer func() {
if doCleanup {
cleanupFunc()
}
}()
file, err := ioutil.TempFile(path, globalPrefix)
if err != nil {
return nil, nil, err
}
doCleanup = false
return file, func() { _ = file.Close(); cleanupFunc() }, nil
}