This repository has been archived by the owner on Apr 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 30
/
file.go
88 lines (75 loc) · 1.96 KB
/
file.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package storage
import (
"io"
"io/ioutil"
"os"
)
// FileStorage saves the content into a file
type FileStorage struct {
file *os.File
subscription *Subscription
}
// NewFileStorage creates a new temp file that will be used as a the storage of the cache entry
func NewFileStorage(path string) (ResponseStorage, error) {
file, err := ioutil.TempFile(path, "caddy-cache-")
if err != nil {
return nil, err
}
return &FileStorage{
file: file,
subscription: NewSubscription(),
}, nil
}
func (f *FileStorage) Write(p []byte) (n int, err error) {
defer f.subscription.NotifyAll(len(p))
return f.file.Write(p)
}
// Flush syncs the underlying file
func (f *FileStorage) Flush() error {
defer f.subscription.NotifyAll(0)
return f.file.Sync()
}
// Clean removes the file
func (f *FileStorage) Clean() error {
f.subscription.WaitAll() // Wait until every subscriber ends waiting every result
return os.Remove(f.file.Name())
}
// Close the underlying file
func (f *FileStorage) Close() error {
f.subscription.Close()
return f.file.Close()
}
// GetReader returns a new file descriptor to the same file
func (f *FileStorage) GetReader() (io.ReadCloser, error) {
newFile, err := os.Open(f.file.Name())
if err != nil {
return nil, err
}
return &FileReader{
content: newFile,
subscription: f.subscription.NewSubscriber(),
unsubscribe: f.subscription.RemoveSubscriber,
}, nil
}
/////////////////////////////////////////
// FileReader is the common code to read the storages until the subscription channel is closed
type FileReader struct {
subscription <-chan int
content io.ReadCloser
unsubscribe func(<-chan int)
}
func (r *FileReader) Read(p []byte) (n int, err error) {
for range r.subscription {
n, err := r.content.Read(p)
if err != io.EOF {
return n, err
}
}
return r.content.Read(p)
}
// Close closes the underlying storage
func (r *FileReader) Close() error {
err := r.content.Close()
r.unsubscribe(r.subscription)
return err
}