douneiben2240 2013-06-17 05:04
浏览 54
已采纳

模板中断http HEAD方法

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

  • 写回答

1条回答 默认 最新

  • douhuifen9942 2013-06-17 13:05
    关注

    The error is self-explaining:

    request method or response status code does not allow body

    A HEAD request only allows HTTP headers to be sent back as response. The real question is why you are able to write to the body in fooHandler.

    EDIT:

    fooHandler won't write anything either, you are omiting the error it is returning which is http.ErrBodyNotAllowed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容