1

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

4

1 回答 1

3

错误是不言自明的:

请求方法或响应状态码不允许正文

HEAD 请求仅允许将 HTTP 标头作为响应发回。真正的问题是为什么你能够在fooHandler.

编辑:

fooHandler也不会写任何东西,你忽略了它返回的错误是http.ErrBodyNotAllowed.

于 2013-06-17T13:05:34.763 回答