-1

I have a Golang template interpreting my html as plain text.

I have included the line w.Header().Set("Content-Type", "text/html; charset=utf-8") in my function passed to http.HandleFunc() however nonetheless my html is interpreted as plain text.

package main

import (
    "html/template"
    "io"
    "net/http"
)

func main() {
    http.HandleFunc("/dog", dog)
    http.Handle("/resources/", http.StripPrefix("/resources", http.FileServer(http.Dir("./assets"))))
    http.ListenAndServe(":8080", nil)
}

var tpl *template.Template

func init() {
    tpl = template.Must(template.ParseFiles("index.gohtml"))
}

func dog(w http.ResponseWriter, req *http.Request) {
    w.Header().Set("Content-Type", "text/html; charset=utf-8")
    data := []string{`<h1>This is from dog</h1>`, `<img src="/assets/img/dog.jpg">`}
    tpl.ExecuteTemplate(w, "index.gohtml", data)
}

And here is my index.gohtml template:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    {{range .}}
        {{.}}
    {{end}}
</body>
</html>
mkopriva
  • 35,176
  • 4
  • 57
  • 71
Peter
  • 119
  • 12
  • Convert your strings to https://golang.org/pkg/html/template/#HTML, either in the Go code, or inside the template by registering a func that does that. E.g. `[]template.HTML{\`

    This is from dog

    \`, \`\`}`
    – mkopriva Jun 21 '19 at 18:34
  • 1
    Thank you @mkopriva that did the trick. I will answer below for others to learn from this. – Peter Jun 21 '19 at 18:40

1 Answers1

1

As pointed out in the comments, the answer is to replace []string{} with []template.HTML{} instead when passed as data into your template.

Peter
  • 119
  • 12