forked from johannesboyne/gofakes3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
range.go
126 lines (103 loc) · 2.53 KB
/
range.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
118
119
120
121
122
123
124
125
126
package gofakes3
import (
"fmt"
"net/http"
"strconv"
"strings"
)
type ObjectRange struct {
Start, Length int64
}
func (o *ObjectRange) writeHeader(sz int64, w http.ResponseWriter) {
if o != nil {
w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", o.Start, o.Start+o.Length-1, sz))
w.Header().Set("Content-Length", fmt.Sprintf("%d", o.Length))
} else {
w.Header().Set("Content-Length", fmt.Sprintf("%d", sz))
}
}
type ObjectRangeRequest struct {
Start, End int64
FromEnd bool
}
const RangeNoEnd = -1
func (o *ObjectRangeRequest) Range(size int64) (*ObjectRange, error) {
if o == nil {
return nil, nil
}
var start, length int64
if !o.FromEnd {
start = o.Start
end := o.End
if o.End == RangeNoEnd {
// If no end is specified, range extends to end of the file.
length = size - start
} else {
length = end - start + 1
}
} else {
// If no start is specified, end specifies the range start relative
// to the end of the file.
end := o.End
start = size - end
length = size - start
}
if start < 0 || length < 0 || start >= size {
return nil, ErrInvalidRange
}
if start+length > size {
return &ObjectRange{Start: start, Length: size - start}, nil
}
return &ObjectRange{Start: start, Length: length}, nil
}
// parseRangeHeader parses a single byte range from the Range header.
//
// Amazon S3 doesn't support retrieving multiple ranges of data per GET request:
// https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGET.html
func parseRangeHeader(s string) (*ObjectRangeRequest, error) {
if s == "" {
return nil, nil
}
const b = "bytes="
if !strings.HasPrefix(s, b) {
return nil, ErrInvalidRange
}
ranges := strings.Split(s[len(b):], ",")
if len(ranges) > 1 {
return nil, ErrorMessage(ErrNotImplemented, "multiple ranges not supported")
}
rnge := strings.TrimSpace(ranges[0])
if len(rnge) == 0 {
return nil, ErrInvalidRange
}
i := strings.Index(rnge, "-")
if i < 0 {
return nil, ErrInvalidRange
}
var o ObjectRangeRequest
start, end := strings.TrimSpace(rnge[:i]), strings.TrimSpace(rnge[i+1:])
if start == "" {
o.FromEnd = true
i, err := strconv.ParseInt(end, 10, 64)
if err != nil {
return nil, ErrInvalidRange
}
o.End = i
} else {
i, err := strconv.ParseInt(start, 10, 64)
if err != nil || i < 0 {
return nil, ErrInvalidRange
}
o.Start = i
if end != "" {
i, err := strconv.ParseInt(end, 10, 64)
if err != nil || o.Start > i {
return nil, ErrInvalidRange
}
o.End = i
} else {
o.End = RangeNoEnd
}
}
return &o, nil
}