From 11eee95222cb5b6fec97f7ce2400f9a1c0617abe Mon Sep 17 00:00:00 2001 From: Jannis Andrija Schnitzer Date: Mon, 7 Oct 2019 18:22:53 +0200 Subject: [PATCH] staticfiles: Signal that redirection headers have been written (#2792) The Handler interface expects a first return value of 0 if headers have already been written. (cf. https://godoc.org/github.com/caddyserver/caddy/caddyhttp/httpserver#Handler) When using http.Redirect, this is the case as http.Redirect does write headers. When using Caddy with nested handlers, returning http.StatusMovedPermanently could cause a wrong (200) response on a non-slashy request on a directory name. Returning 0 ensures the redirection will always take place. --- caddyhttp/staticfiles/fileserver.go | 4 ++-- caddyhttp/staticfiles/fileserver_test.go | 3 +++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/caddyhttp/staticfiles/fileserver.go b/caddyhttp/staticfiles/fileserver.go index 5690ceb9..65ae322b 100644 --- a/caddyhttp/staticfiles/fileserver.go +++ b/caddyhttp/staticfiles/fileserver.go @@ -116,7 +116,7 @@ func (fs FileServer) serveFile(w http.ResponseWriter, r *http.Request) (int, err } urlCopy.Path += "/" http.Redirect(w, r, urlCopy.String(), http.StatusMovedPermanently) - return http.StatusMovedPermanently, nil + return 0, nil } } else { // ensure no trailing slash @@ -143,7 +143,7 @@ func (fs FileServer) serveFile(w http.ResponseWriter, r *http.Request) (int, err urlCopy.Path = strings.TrimPrefix(urlCopy.Path, "/") } http.Redirect(w, r, urlCopy.String(), http.StatusMovedPermanently) - return http.StatusMovedPermanently, nil + return 0, nil } } diff --git a/caddyhttp/staticfiles/fileserver_test.go b/caddyhttp/staticfiles/fileserver_test.go index a534d8c8..8425c202 100644 --- a/caddyhttp/staticfiles/fileserver_test.go +++ b/caddyhttp/staticfiles/fileserver_test.go @@ -301,6 +301,9 @@ func TestServeHTTP(t *testing.T) { // perform the test status, err := fileServer.ServeHTTP(responseRecorder, request) + if status == 0 { + status = responseRecorder.Code + } etag := responseRecorder.Header().Get("Etag") body := responseRecorder.Body.String() vary := responseRecorder.Header().Get("Vary")