/
serve.go
218 lines (188 loc) · 5.31 KB
/
serve.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package serve
import (
"bytes"
"compress/gzip"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"mime"
"net/http"
"path"
"regexp"
"strconv"
"strings"
"time"
"github.com/koud-fi/pkg/blob"
)
var ErrContentLengthMismatch = errors.New("content-length mismatch")
var rangeParser = regexp.MustCompile(`bytes=(\d+)-(\d+)?`)
type Option func(c *config)
type config struct{ Info }
type Info struct {
StatusCode int
ContentLength int64
ContentType string
Location string
LastModified time.Time
MaxAge time.Duration
Immutable bool
Compress bool
Disposition string
Range *[2]int64
}
func StatusCode(n int) Option { return func(c *config) { c.StatusCode = n } }
func ContentLength(n int64) Option { return func(c *config) { c.ContentLength = n } }
func ContentType(ct string) Option { return func(c *config) { c.ContentType = ct } }
func Location(loc string) Option { return func(c *config) { c.Location = loc } }
func LastModified(t time.Time) Option { return func(c *config) { c.LastModified = t } }
func MaxAge(d time.Duration) Option { return func(c *config) { c.MaxAge = d } }
func Compress(b bool) Option { return func(c *config) { c.Compress = b } }
func Immutable(b bool) Option { return func(c *config) { c.Immutable = b } }
func NoOp() Option { return func(_ *config) {} }
func Attachment(name string) Option {
return func(c *config) {
if name == "" {
c.Disposition = ""
}
c.Disposition = fmt.Sprintf(`attachment; filename="%s"`, name)
}
}
func Range(start, end int64) Option {
return func(c *config) { c.Range = &[2]int64{start, end} }
}
func ContentTypeFromPath(p string) Option {
if ext := path.Ext(p); ext != "" {
return ContentType(mime.TypeByExtension(ext))
}
return NoOp()
}
func Header(w http.ResponseWriter, opt ...Option) (*Info, error) {
c := buildConfig(opt)
c.writeHeader(w)
return &c.Info, nil
}
func JSON(w http.ResponseWriter, r *http.Request, v any, opt ...Option) (*Info, error) {
return Blob(w, r, blob.Marshal(json.Marshal, v),
ContentType("application/json; charset=utf-8"))
}
func Blob(w http.ResponseWriter, r *http.Request, b blob.Blob, opt ...Option) (*Info, error) {
rc, err := b.Open()
if err != nil {
return nil, err
}
defer rc.Close()
return Reader(w, r, rc, opt...)
}
func Reader(rw http.ResponseWriter, r *http.Request, rd io.Reader, opt ...Option) (*Info, error) {
var c = buildConfig(opt)
if br, ok := rd.(blob.BytesReader); ok {
buf := br.Bytes()
c.ContentLength = int64(len(buf))
// TODO: detect content-type
rd = bytes.NewReader(buf)
} else {
if f, ok := rd.(fs.File); ok {
info, err := f.Stat()
if err != nil {
return nil, err
}
c.ContentLength = info.Size()
c.LastModified = info.ModTime()
}
// TODO: detect content-type
}
w := io.Writer(rw)
// TODO: support range requests with io.Seeker
if rat, ok := rd.(io.ReaderAt); ok {
rw.Header().Set("Accept-Ranges", "bytes")
if rh := r.Header.Get("Range"); rh != "" {
begin, end := parseRangeHeader(rh, c.ContentLength)
buf := make([]byte, end-begin)
if _, err := rat.ReadAt(buf, begin); err != nil {
return nil, err
}
rw.Header().Set("Content-Range",
fmt.Sprintf("bytes %d-%d/%d", begin, end-1, c.ContentLength))
c.StatusCode = http.StatusPartialContent
w = bytes.NewBuffer(buf)
}
}
if c.Compress {
rw.Header().Set("Vary", "Content-Encoding")
if c.ContentLength > 1400 && strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
c.ContentLength = -1
rw.Header().Set("Content-Encoding", "gzip")
gw := gzip.NewWriter(w)
defer gw.Flush()
w = gw
} else {
c.Compress = false
}
}
c.writeHeader(rw)
if n, err := io.Copy(w, rd); err != nil {
return nil, err
} else if c.ContentLength > 0 && c.ContentLength != n {
return nil, ErrContentLengthMismatch
} else {
c.ContentLength = n
}
return &c.Info, nil
}
func buildConfig(opt []Option) (c config) {
for _, opt := range opt {
opt(&c)
}
if c.StatusCode == 0 {
c.StatusCode = http.StatusOK
}
return
}
func (nfo Info) writeHeader(w http.ResponseWriter) {
if nfo.ContentLength > 0 {
w.Header().Set("Content-Length", strconv.FormatInt(nfo.ContentLength, 10))
}
if nfo.ContentType != "" {
w.Header().Set("Content-Type", nfo.ContentType)
}
if nfo.Location != "" {
w.Header().Set("Location", nfo.Location)
}
if !nfo.LastModified.IsZero() {
w.Header().Set("Last-Modified", nfo.LastModified.Format(http.TimeFormat))
}
if nfo.MaxAge > 0 || nfo.Immutable {
if nfo.Immutable && nfo.MaxAge == 0 {
nfo.MaxAge = time.Hour * 24 * 365 // year
}
v := "public, max-age=" + strconv.Itoa(int(nfo.MaxAge/time.Second))
if nfo.Immutable {
v += ", immutable"
}
w.Header().Set("Cache-Control", v)
}
if nfo.Disposition != "" {
w.Header().Set("Content-Disposition", nfo.Disposition)
}
if nfo.Range != nil {
w.Header().Set("Range", fmt.Sprintf("%d-%d", nfo.Range[0], nfo.Range[1]))
}
w.WriteHeader(nfo.StatusCode)
}
func parseRangeHeader(s string, size int64) (int64, int64) {
const bufSize = 1 << 22 // 4 MB
var (
sms = rangeParser.FindStringSubmatch(s)
begin, _ = strconv.ParseInt(sms[1], 10, 64)
end, _ = strconv.ParseInt(sms[2], 10, 64)
)
if end <= 0 || end == begin || end-begin > bufSize {
end = begin + bufSize
if end > size {
end = size
}
}
return begin, end
}