Consider this code: when I GET http://localhost:8080/
or http://localhost:8080/foo
everything works as expected. But when I use the HEAD http method, http://localhost:8080/foo
works but http://localhost:8080/
breaks (the main program exits and I get this error: 'template: main.html:1:0: executing "main.html" at <"homeHandler">: http: request method or response status code does not allow body'). The difference between those two is the use of the template in one case (/
) and a simple string in the other(/foo
).
In my code I use templates extensively, so it looks like I have to ask explicitly for the method and return "200" (or the appropriate code). Is there a way to have templates and the automatic handling of the HEAD method?
I have tried these to test: curl http://localhost:8080/foo -I
(-I
for the HEAD method).
package main
import (
"html/template"
"log"
"net/http"
)
var (
templates *template.Template
)
// OK, HEAD + GET work fine
func fooHandler(w http.ResponseWriter, req *http.Request) {
w.Write([]byte("fooHandler"))
}
// GET works fine, HEAD results in an error:
// template: main.html:1:0: executing "main.html" at <"homeHandler">:
// http: request method or response status code does not allow body
func homeHandler(w http.ResponseWriter, req *http.Request) {
err := templates.ExecuteTemplate(w, "main.html", nil)
if err != nil {
log.Fatal(err)
}
}
func main() {
var err error
templates, err = template.ParseGlob("templates/*.html")
if err != nil {
log.Fatal("Loading template: ", err)
}
http.HandleFunc("/", homeHandler)
http.HandleFunc("/foo", fooHandler)
http.ListenAndServe(":8080", nil)
}
The file main.html
in the subdirectory templates
is just this string: homeHandler