From 4a095590b1fdb75312f8d7e8a436d5b864a57771 Mon Sep 17 00:00:00 2001 From: crvv Date: Tue, 28 Feb 2017 18:14:52 +0800 Subject: [PATCH] templates: Set right response Content-Type If use gzip and templates at the same time, the response body will be gzipped data. And in this case, the Content-Type header won't be set by Caddy code. Then Go http package will set "Content-Type" to wrong value "application/x-gzip" which is determined by response body. So the header Contenty-Type should be set in templates middleware. --- caddyhttp/templates/templates.go | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/caddyhttp/templates/templates.go b/caddyhttp/templates/templates.go index 91491f11..afc6fbe3 100644 --- a/caddyhttp/templates/templates.go +++ b/caddyhttp/templates/templates.go @@ -4,6 +4,7 @@ package templates import ( "bytes" + "mime" "net/http" "os" "path" @@ -62,6 +63,16 @@ func (t Templates) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error return http.StatusInternalServerError, err } + // If Content-Type isn't set here, http.ResponseWriter.Write + // will set it according to response body. But other middleware + // such as gzip can modify response body, then Content-Type + // detected by http.ResponseWriter.Write is wrong. + ctype := mime.TypeByExtension(ext) + if ctype == "" { + ctype = http.DetectContentType(buf.Bytes()) + } + w.Header().Set("Content-Type", ctype) + templateInfo, err := os.Stat(templatePath) if err == nil { // add the Last-Modified header if we were able to read the stamp