1

次のコードを考えてみましょう: GEThttp://localhost:8080/またはhttp://localhost:8080/fooすべてが期待どおりに機能する場合。しかし、HEAD http メソッドを使用すると、http://localhost:8080/foo機能しますがhttp://localhost:8080/壊れます (メイン プログラムが終了し、次のエラーが発生します: 'template: main.html:1:0: running "main.html" at <"homeHandler">: http: requestメソッドまたは応答のステータス コードでは、本文は許可されません')。これら 2 つの違いは、テンプレートを使用するケース ( /) と単純な文字列を使用するケース ( /foo) です。

私のコードではテンプレートを広範囲に使用しているため、メソッドを明示的に要求して「200」(または適切なコード) を返す必要があるようです。テンプレートと HEAD メソッドの自動処理を行う方法はありますか?

これらをテストしてみました:curl http://localhost:8080/foo -I-IHEADメソッドの場合)。

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

4

1 に答える 1

3

エラーは自明です:

リクエスト メソッドまたはレスポンス ステータス コードで本文が許可されていません

HEAD リクエストでは、HTTP ヘッダーのみをレスポンスとして送り返すことができます。本当の問題は、なぜ本体に書き込みができるのかということですfooHandler

編集:

fooHandlerどちらも何も書きません。返されるエラーを省略していますhttp.ErrBodyNotAllowed

于 2013-06-17T13:05:34.763 に答える