0
Fork 0
mirror of https://github.com/caddyserver/caddy.git synced 2025-01-13 22:51:08 -05:00

Errors: Hiding HTTP error messages #567

This commit is contained in:
Benoit Benedetti 2016-02-19 14:42:44 +01:00
parent bec130a563
commit 8c150894e5
3 changed files with 18 additions and 4 deletions

View file

@ -27,7 +27,8 @@ type ErrorHandler struct {
func (h ErrorHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
defer h.recovery(w, r)
status, err := h.Next.ServeHTTP(w, r)
responseRecorder := middleware.NewResponseRecorder(w)
status, err := h.Next.ServeHTTP(responseRecorder, r)
if err != nil {
errMsg := fmt.Sprintf("%s [ERROR %d %s] %v", time.Now().Format(timeFormat), status, r.URL.Path, err)
@ -36,14 +37,17 @@ func (h ErrorHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, er
// Write error to response instead of to log
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(status)
fmt.Fprintln(w, errMsg)
fmt.Fprintln(responseRecorder, errMsg)
return 0, err // returning < 400 signals that a response has been written
}
h.Log.Println(errMsg)
}
if status >= 400 {
h.errorPage(w, r, status)
// Check there is no response body already sent
if responseRecorder.Size() == 0 {
h.errorPage(responseRecorder, r, status)
}
return 0, err
}

View file

@ -78,6 +78,13 @@ func TestErrors(t *testing.T) {
expectedLog: "",
expectedErr: nil,
},
{
next: genErrorHandler(http.StatusNotFound, nil, "normal"),
expectedCode: 0,
expectedBody: "normal",
expectedLog: "",
expectedErr: nil,
},
{
next: genErrorHandler(http.StatusForbidden, nil, ""),
expectedCode: 0,

View file

@ -320,7 +320,10 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Fallback error response in case error handling wasn't chained in
if status >= 400 {
DefaultErrorFunc(w, r, status)
// Check there is no response body already sent
if w.Header().Get("Content-Length") == "" {
DefaultErrorFunc(w, r, status)
}
}
} else {
// Get the remote host