From 7b0962ba4df7e1dd7ab3f193fba394a4b899c431 Mon Sep 17 00:00:00 2001 From: Matthew Holt Date: Thu, 4 Jun 2020 10:32:01 -0600 Subject: caddyhttp: Default to error status if found in context This is just a convenience if using a static_response handler in an error route, by setting the default status code to the same one as the error status. --- modules/caddyhttp/staticresp.go | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) (limited to 'modules/caddyhttp/staticresp.go') diff --git a/modules/caddyhttp/staticresp.go b/modules/caddyhttp/staticresp.go index 3841a26..0a568fc 100644 --- a/modules/caddyhttp/staticresp.go +++ b/modules/caddyhttp/staticresp.go @@ -121,8 +121,16 @@ func (s StaticResponse) ServeHTTP(w http.ResponseWriter, r *http.Request, _ Hand w.Header()["Content-Type"] = nil } - // get the status code + // get the status code; if this handler exists in an error route, + // use the recommended status code as the default; otherwise 200 statusCode := http.StatusOK + if reqErr, ok := r.Context().Value(ErrorCtxKey).(error); ok { + if handlerErr, ok := reqErr.(HandlerError); ok { + if handlerErr.StatusCode > 0 { + statusCode = handlerErr.StatusCode + } + } + } if codeStr := s.StatusCode.String(); codeStr != "" { intVal, err := strconv.Atoi(repl.ReplaceAll(codeStr, "")) if err != nil { -- cgit v1.2.3