This repository has been archived by the owner on Oct 22, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathbody_size_limit.go
58 lines (51 loc) · 1.62 KB
/
body_size_limit.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
package bitsgo
import (
"io"
"io/ioutil"
"net/http"
"github.com/cloudfoundry-incubator/bits-service/logger"
)
// Note: this changes the request under certain conditions
func HandleBodySizeLimits(responseWriter http.ResponseWriter, request *http.Request, maxBodySizeLimit uint64) (shouldContinue bool) {
if maxBodySizeLimit != 0 {
logger.From(request).Debugw("max-body-size is enabled", "max-body-size", maxBodySizeLimit)
if request.ContentLength == -1 {
badRequest(responseWriter, request, "HTTP header does not contain Content-Length")
return
}
if uint64(request.ContentLength) > maxBodySizeLimit {
defer request.Body.Close()
// Reading the body here is really just to make Ruby's RestClient happy.
// For some reason it crashes if we don't read the body.
io.Copy(ioutil.Discard, request.Body)
responseWriter.WriteHeader(http.StatusRequestEntityTooLarge)
return
}
request.Body = &limitedReader{request.Body, request.ContentLength}
}
shouldContinue = true
return
}
// Copied more or less from io.LimitedReader
type limitedReader struct {
delegate io.Reader
maxBytesRemaining int64
}
func (l *limitedReader) Read(p []byte) (n int, err error) {
if l.maxBytesRemaining <= 0 {
return 0, io.EOF
}
if int64(len(p)) > l.maxBytesRemaining {
p = p[0:l.maxBytesRemaining]
}
n, err = l.delegate.Read(p)
l.maxBytesRemaining -= int64(n)
return
}
func (l *limitedReader) Close() error {
// Reading the body here is really just to make Ruby's RestClient happy.
// For some reason it crashes if we don't read the body.
io.Copy(ioutil.Discard, l.delegate)
// TODO Should we return errors?
return nil
}