From d5a62defba1118f0250a38d5fc8d3939d3433d73 Mon Sep 17 00:00:00 2001 From: DarthSim Date: Wed, 27 Jul 2022 17:11:07 +0600 Subject: [PATCH] Set proper ContentLength for 404 responses in FS transport --- transport/fs/fs.go | 42 ++++++++++++++++-------------------------- 1 file changed, 16 insertions(+), 26 deletions(-) diff --git a/transport/fs/fs.go b/transport/fs/fs.go index 2ac80a55..7a3675e8 100644 --- a/transport/fs/fs.go +++ b/transport/fs/fs.go @@ -27,19 +27,7 @@ func (t transport) RoundTrip(req *http.Request) (resp *http.Response, err error) f, err := t.fs.Open(req.URL.Path) if err != nil { if os.IsNotExist(err) { - return &http.Response{ - StatusCode: http.StatusNotFound, - Proto: "HTTP/1.0", - ProtoMajor: 1, - ProtoMinor: 0, - Header: header, - ContentLength: 0, - Body: io.NopCloser(strings.NewReader( - fmt.Sprintf("%s doesn't exist", req.URL.Path), - )), - Close: false, - Request: req, - }, nil + return respNotFound(req, fmt.Sprintf("%s doesn't exist", req.URL.Path)), nil } return nil, err } @@ -50,19 +38,7 @@ func (t transport) RoundTrip(req *http.Request) (resp *http.Response, err error) } if fi.IsDir() { - return &http.Response{ - StatusCode: http.StatusNotFound, - Proto: "HTTP/1.0", - ProtoMajor: 1, - ProtoMinor: 0, - Header: header, - ContentLength: 0, - Body: io.NopCloser(strings.NewReader( - fmt.Sprintf("%s is directory", req.URL.Path), - )), - Close: false, - Request: req, - }, nil + return respNotFound(req, fmt.Sprintf("%s is directory", req.URL.Path)), nil } if config.ETagEnabled { @@ -105,3 +81,17 @@ func BuildEtag(path string, fi fs.FileInfo) string { hash := md5.Sum([]byte(tag)) return `"` + string(base64.RawURLEncoding.EncodeToString(hash[:])) + `"` } + +func respNotFound(req *http.Request, msg string) *http.Response { + return &http.Response{ + StatusCode: http.StatusNotFound, + Proto: "HTTP/1.0", + ProtoMajor: 1, + ProtoMinor: 0, + Header: make(http.Header), + ContentLength: int64(len(msg)), + Body: io.NopCloser(strings.NewReader(msg)), + Close: false, + Request: req, + } +}