When trying to pass a value into .html
code I'm using the html/template
package.
However, I can't seem to set the .css
content type that is referenced in my .html
file. It is being served to the browser as plain text and thus formatting is ignored.
In a static .html
file I can use the built-in http.Fileserver
which takes care of content types but then templating doesn't work. I can't pass in the variable. It just displays as {{.}}
Is there a way to combine the content-type
convenience of the built-in fileserver http.Fileserver
with the template ability of http.HandleFunc
?
Here is my code as it stands without using http.Fileserver
. Note, my Go
file is in the starting directory and the index.html
and .css
files are in a subdirectory /hello/
:
package main
import (
"html/template"
"io/ioutil"
"log"
"net/http"
)
var Message string = "test page"
func servePipe(w http.ResponseWriter, req *http.Request) {
dat, err := ioutil.ReadFile("hello/index.html")
if err != nil {
log.Fatal("couldn't read file:", err)
}
templ, err := template.New("Test").Parse(string(dat))
if err != nil {
log.Fatal("couldn't parse page:", err)
}
templ.Execute(w, Message)
}
func main() {
http.HandleFunc("/hello/", servePipe)
http.ListenAndServe(":8080", nil)
}
Here is my .html
file. The html page is being served without any issues. It's the separate .css
file that is not being served (linked in the .html
file) thus the formatting doesn't occur.
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<p>{{.}}</p>
</body>
</html>