forked from cavaliergopher/grab
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
161 lines (143 loc) · 3.57 KB
/
handler.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
package grabtest
import (
"bufio"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
)
var (
DefaultHandlerContentLength = 1 << 20
DefaultHandlerMD5Checksum = "c35cc7d8d91728a0cb052831bc4ef372"
DefaultHandlerMD5ChecksumBytes = MustHexDecodeString(DefaultHandlerMD5Checksum)
DefaultHandlerSHA256Checksum = "fbbab289f7f94b25736c58be46a994c441fd02552cc6022352e3d86d2fab7c83"
DefaultHandlerSHA256ChecksumBytes = MustHexDecodeString(DefaultHandlerSHA256Checksum)
)
type StatusCodeFunc func(req *http.Request) int
type handler struct {
statusCodeFunc StatusCodeFunc
methodWhitelist []string
headerBlacklist []string
contentLength int
acceptRanges bool
attachmentFilename string
lastModified time.Time
ttfb time.Duration
rateLimiter *time.Ticker
}
func NewHandler(options ...HandlerOption) (http.Handler, error) {
h := &handler{
statusCodeFunc: func(req *http.Request) int { return http.StatusOK },
methodWhitelist: []string{"GET", "HEAD"},
contentLength: DefaultHandlerContentLength,
acceptRanges: true,
}
for _, option := range options {
if err := option(h); err != nil {
return nil, err
}
}
return h, nil
}
func WithTestServer(t *testing.T, f func(url string), options ...HandlerOption) {
h, err := NewHandler(options...)
if err != nil {
t.Fatalf("unable to create test server handler: %v", err)
return
}
s := httptest.NewServer(h)
defer func() {
h.(*handler).close()
s.Close()
}()
f(s.URL)
}
func (h *handler) close() {
if h.rateLimiter != nil {
h.rateLimiter.Stop()
}
}
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// delay response
if h.ttfb > 0 {
time.Sleep(h.ttfb)
}
// validate request method
allowed := false
for _, m := range h.methodWhitelist {
if r.Method == m {
allowed = true
break
}
}
if !allowed {
httpError(w, http.StatusMethodNotAllowed)
return
}
// set server options
if h.acceptRanges {
w.Header().Set("Accept-Ranges", "bytes")
}
// set attachment filename
if h.attachmentFilename != "" {
w.Header().Set(
"Content-Disposition",
fmt.Sprintf("attachment;filename=\"%s\"", h.attachmentFilename),
)
}
// set last modified timestamp
lastMod := time.Now()
if !h.lastModified.IsZero() {
lastMod = h.lastModified
}
w.Header().Set("Last-Modified", lastMod.Format(http.TimeFormat))
// set content-length
offset := 0
if h.acceptRanges {
if reqRange := r.Header.Get("Range"); reqRange != "" {
if _, err := fmt.Sscanf(reqRange, "bytes=%d-", &offset); err != nil {
httpError(w, http.StatusBadRequest)
return
}
if offset >= h.contentLength {
httpError(w, http.StatusRequestedRangeNotSatisfiable)
return
}
}
}
w.Header().Set("Content-Length", fmt.Sprintf("%d", h.contentLength-offset))
// apply header blacklist
for _, key := range h.headerBlacklist {
w.Header().Del(key)
}
// send header and status code
w.WriteHeader(h.statusCodeFunc(r))
// send body
if r.Method == "GET" {
// use buffered io to reduce overhead on the reader
bw := bufio.NewWriterSize(w, 4096)
for i := offset; !isRequestClosed(r) && i < h.contentLength; i++ {
bw.Write([]byte{byte(i)})
if h.rateLimiter != nil {
<-h.rateLimiter.C
}
}
if !isRequestClosed(r) {
bw.Flush()
}
}
}
// isRequestClosed returns true if the client request has been canceled.
func isRequestClosed(r *http.Request) bool {
ctx := r.Context()
select {
case <-ctx.Done():
return true
default:
return false
}
}
func httpError(w http.ResponseWriter, code int) {
http.Error(w, http.StatusText(code), code)
}