From 3f6283b385642c56f34b479d1275095379b062d3 Mon Sep 17 00:00:00 2001 From: Francis Lavoie Date: Thu, 8 Apr 2021 13:09:12 -0400 Subject: fileserver: Add status code override (#4076) After reading a question about the `handle_response` feature of `reverse_proxy`, I realized that we didn't have a way of serving an arbitrary file with a status code other than 200. This is an issue in situations where you want to serve a custom error page in routes that are not errors, like the aforementioned `handle_response`, where you may want to retain the status code returned by the proxy but write a response with content from a file. This feature is super simple, basically if a status code is configured (can be a status code number, or a placeholder string) then that status will be written out before serving the file - if we write the status code first, then the stdlib won't write its own (only the first HTTP status header wins). --- modules/caddyhttp/fileserver/caddyfile.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'modules/caddyhttp/fileserver/caddyfile.go') diff --git a/modules/caddyhttp/fileserver/caddyfile.go b/modules/caddyhttp/fileserver/caddyfile.go index 2ba53f2..447f481 100644 --- a/modules/caddyhttp/fileserver/caddyfile.go +++ b/modules/caddyhttp/fileserver/caddyfile.go @@ -40,6 +40,7 @@ func init() { // index // browse [] // precompressed +// status // } // func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { @@ -65,21 +66,25 @@ func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) if len(fsrv.Hide) == 0 { return nil, h.ArgErr() } + case "index": fsrv.IndexNames = h.RemainingArgs() if len(fsrv.IndexNames) == 0 { return nil, h.ArgErr() } + case "root": if !h.Args(&fsrv.Root) { return nil, h.ArgErr() } + case "browse": if fsrv.Browse != nil { return nil, h.Err("browsing is already configured") } fsrv.Browse = new(Browse) h.Args(&fsrv.Browse.TemplateFile) + case "precompressed": var order []string for h.NextArg() { @@ -100,6 +105,13 @@ func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) order = append(order, h.Val()) } fsrv.PrecompressedOrder = order + + case "status": + if !h.NextArg() { + return nil, h.ArgErr() + } + fsrv.StatusCode = caddyhttp.WeakString(h.Val()) + default: return nil, h.Errf("unknown subdirective '%s'", h.Val()) } -- cgit v1.2.3