forked from juneym/gor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
input_file.go
76 lines (57 loc) · 1.17 KB
/
input_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
package main
import (
"encoding/gob"
"log"
"os"
"time"
)
type FileInput struct {
data chan []byte
path string
decoder *gob.Decoder
speedFactor float64
}
func NewFileInput(path string) (i *FileInput) {
i = new(FileInput)
i.data = make(chan []byte)
i.path = path
i.speedFactor = 1
i.Init(path)
go i.emit()
return
}
func (i *FileInput) Init(path string) {
file, err := os.Open(path)
if err != nil {
log.Fatal(i, "Cannot open file %q. Error: %s", path, err)
}
i.decoder = gob.NewDecoder(file)
}
func (i *FileInput) Read(data []byte) (int, error) {
buf := <-i.data
copy(data, buf)
return len(buf), nil
}
func (i *FileInput) String() string {
return "File input: " + i.path
}
func (i *FileInput) emit() {
var lastTime int64
for {
raw := new(RawRequest)
err := i.decoder.Decode(raw)
if err != nil {
return
}
if lastTime != 0 {
timeDiff := raw.Timestamp - lastTime
// We can speedup or slowdown execution based on speedFactor
if i.speedFactor != 1 {
timeDiff = int64(float64(raw.Timestamp-lastTime) / i.speedFactor)
}
time.Sleep(time.Duration(timeDiff))
}
lastTime = raw.Timestamp
i.data <- raw.Request
}
}