Force Content-Type to text/html when rendering a template

By chance, i found out that sometimes Go returned a Content-Type header
of text/plain for some responses to HTMx request.  Go’s documentation
for http.ResponseWriter.Write sheds some light to this issue:

> If the Header does not contain a Content-Type line, Write adds a
> Content-Type set to the result of passing the initial 512 bytes of
> written data to DetectContentType.

http.DetectContentType has “sniff signatures” for the most common HTML
elements, such as `<BODY`, `<P`, or even `<!--`, but when the template
only has elements not in that list, the text “text sniff signature”
kicks in because the content does not contain binary data bytes, as
specified in [0], §7.1, step 9.

I can not change mustRenderTemplate’s wr parameter, and its callers’,
to be of type http.ResponseWriter because mustWriteInvoicePdf writes
the template to a pipe object, which is not of this type.  Thus, i have
to resort to type assertion inside the method.

[0]: https://mimesniff.spec.whatwg.org/#identifying-a-resource-with-an-unknown-mime-type
This commit is contained in:
jordi fita mas 2023-04-29 15:59:26 +02:00
parent d941adcdfe
commit 4162da3a06
1 changed files with 3 additions and 0 deletions

View File

@ -84,6 +84,9 @@ func mustRenderTemplate(wr io.Writer, r *http.Request, layout string, filename s
if _, err := t.ParseFiles(templateFile(filename), templateFile(layout), templateFile("form.gohtml")); err != nil {
panic(err)
}
if w, ok := wr.(http.ResponseWriter); ok {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
}
if err := t.ExecuteTemplate(wr, layout, data); err != nil {
panic(err)
}