-
Notifications
You must be signed in to change notification settings - Fork 0
/
chunks.go
117 lines (94 loc) · 1.8 KB
/
chunks.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
109
110
111
112
113
114
115
116
117
package filepond
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
)
type ChunkManager struct {
filename string
totalSize uint64
dir string
offset uint64
chunkFiles []string
}
func NewChunkManager(dir, filename string, totalSize uint64) *ChunkManager {
return &ChunkManager{
filename: filename,
dir: dir,
totalSize: totalSize,
}
}
func (c *ChunkManager) Append(r io.ReadCloser) error {
err := c.saveChunk(r)
if err != nil {
return err
}
if !c.Finish() {
return nil
}
err = c.merge()
if err != nil {
return err
}
return c.clean()
}
func (c *ChunkManager) Offset() uint64 {
return c.offset
}
func (c *ChunkManager) saveChunk(r io.ReadCloser) error {
defer r.Close()
name := filepath.Join(c.dir, fmt.Sprintf("%d.chunk", c.offset))
f, err := os.Create(name)
if err != nil {
return err
}
defer f.Close()
n, err := io.Copy(f, r)
if err != nil {
return err
}
c.offset += uint64(n)
if c.offset > c.totalSize {
return errors.New("received data length more than totalsize")
}
c.chunkFiles = append(c.chunkFiles, name)
return nil
}
func (c *ChunkManager) merge() error {
f, err := os.Create(filepath.Join(c.dir, c.filename))
if err != nil {
return err
}
defer f.Close()
var n int64
for _, namePath := range c.chunkFiles {
chunkFile, err := os.Open(namePath)
if err != nil {
return err
}
_n, err := io.Copy(f, chunkFile)
chunkFile.Close() // close chunk file
if err != nil {
return err
}
n += _n
}
if uint64(n) != c.totalSize {
return errors.New("merge file size incorrect")
}
return nil
}
func (c *ChunkManager) clean() error {
for _, namePath := range c.chunkFiles {
err := os.Remove(namePath)
if err != nil {
return err
}
}
return nil
}
func (c *ChunkManager) Finish() bool {
return c.totalSize == c.offset
}