-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransformer.go
81 lines (67 loc) · 1.8 KB
/
transformer.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
package multipart
import (
"bytes"
"fmt"
"io"
)
// TODO: this is introduced in Go 1.16
type ReadSeekCloser interface {
io.Reader
io.Seeker
io.Closer
}
type Transformer struct {
src ReadSeekCloser
boundary string
parts []*Part
}
func NewTransformer(src ReadSeekCloser, parts []*Part) *Transformer {
boundary := randomBoundary()
return NewTransformerWithBoundary(src, parts, boundary)
}
func NewTransformerWithBoundary(src ReadSeekCloser, parts []*Part, boundary string) *Transformer {
return &Transformer{
src: src,
boundary: boundary,
parts: parts,
}
}
func (tfm *Transformer) SetBoundary(boundary string) {
tfm.boundary = boundary
}
func (tfm *Transformer) ContentLength() int64 {
var buf bytes.Buffer
partsBodyLen := int64(0)
for _, part := range tfm.parts {
partsBodyLen += part.rangeEndInt - part.rangeStartInt + 1
tfm.WritePartHeader(&buf, part)
}
fmt.Fprintf(&buf, "\r\n--%s--", tfm.boundary)
partsHeaderLen := int64(buf.Len())
// the first CRLF is not part of message body
// ref: https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html
return partsHeaderLen + partsBodyLen - 2
}
func (tfm *Transformer) WritePartHeader(buf io.Writer, part *Part) error {
fmt.Fprintf(buf, "\r\n--%s\r\n", tfm.boundary)
fmt.Fprint(buf, "Content-Type: application/octet-stream\r\n")
fmt.Fprintf(buf, "Content-Range: bytes %s-%s/%s\r\n", part.rangeStart, part.rangeEnd, part.fileSize)
fmt.Fprint(buf, "\r\n")
return nil
}
func (tfm *Transformer) WriteMultiParts(wt io.Writer) error {
var err error
for _, part := range tfm.parts {
if err = tfm.WritePartHeader(wt, part); err != nil {
return err
}
if err = writePartBody(tfm.src, wt, part); err != nil {
return err
}
}
_, err = fmt.Fprintf(wt, "\r\n--%s--", tfm.boundary)
if err != nil {
return err
}
return nil
}