模板打破了http HEAD方法

时间:2013-06-17 05:04:52

标签: templates go

考虑以下代码:当我获取http://localhost:8080/http://localhost:8080/foo时,一切都按预期工作。但是当我使用HEAD http方法时,http://localhost:8080/foo可以正常工作,但http://localhost:8080/会中断(主程序退出,我收到此错误:'template:main.html:1:0:执行“main.html” at<“homeHandler”>:http:请求方法或响应状态代码不允许body')。这两者之间的区别在于在一种情况下使用模板(/)而在另一种情况下使用简单的字符串(/foo)。

在我的代码中,我广泛使用模板,所以看起来我必须明确询问方法并返回“200”(或相应的代码)。有没有办法让模板和HEAD方法自动处理?

我已尝试过这些测试:curl http://localhost:8080/foo -I(HEAD方法的-I)。

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)
}

子目录main.html中的文件templates就是这个字符串:homeHandler

1 个答案:

答案 0 :(得分:3)

错误是自我解释:

  

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

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

编辑:

fooHandler也不会写任何内容,你要忽略它返回的错误http.ErrBodyNotAllowed