-
Notifications
You must be signed in to change notification settings - Fork 15
/
file.go
108 lines (95 loc) · 2.27 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package goexpress
import (
"io"
"os"
"sync"
)
const (
_mode = 0644
)
type fileHandler struct {
offset int64
bufferSize int64
f *os.File
}
// readIntent returns the chunk that has been read
type readIntent struct {
data []byte
err error
}
// monitor monitors the read thread and help sync
// between consumer and producer
type monitor struct {
sync.Mutex
stopChannel chan bool
}
func newFile(url string, bufferSize int64) (*fileHandler, error) {
fh := &fileHandler{}
file, err := os.Open(url)
if err != nil {
return nil, err
}
fh.f = file
if bufferSize == 0 {
bufferSize = MaxBufferSize
}
// assign the buffersize
fh.bufferSize = bufferSize
return fh, nil
}
// Stat returns fileinfo of the file
func (fh *fileHandler) Stat() (os.FileInfo, error) {
return fh.f.Stat()
}
func (fh *fileHandler) Pipe(resp *response) (bool, error) {
// create a single value buffered channel
channel := make(chan *readIntent, 1)
threadMonitor := &monitor{
// create a single cap channel
stopChannel: make(chan bool, 1),
}
// spin up a read thread
go fh.readThread(channel, threadMonitor)
for {
// read from the channel
intent := <-channel
// if there was an error, check the error and return
if intent.err != nil {
// notify thread to stop
threadMonitor.stopChannel <- true
if intent.err == io.EOF {
// flush the last bytes and exit
resp.WriteBytes(intent.data)
resp.End()
return true, nil
}
return false, intent.err
}
// in case of no error, write the bytes
err := resp.WriteBytes(intent.data)
if err != nil {
// stop the file reader go-routine
threadMonitor.stopChannel <- true
return false, err
}
}
}
func (fh *fileHandler) readThread(channel chan *readIntent, threadMonitor *monitor) {
// loop over until we exhaust the stream
for {
intent := &readIntent{}
// create a read buffer
data := make([]byte, fh.bufferSize)
n, err := fh.f.ReadAt(data, fh.offset)
// update the offset and return the struct
fh.offset += int64(n)
// trim buffer
intent.data = data[:n]
intent.err = err
select {
case <-threadMonitor.stopChannel:
return
case channel <- intent:
}
}
}