亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何攔截錯誤的http HEAD請求

如何攔截錯誤的http HEAD請求

Go
慕田峪7331174 2023-08-07 15:10:39
有沒有辦法在 Go HTTP 服務器中攔截錯誤的 HEAD 請求?這里的錯誤請求是發送帶有 HEAD 請求的 JSON 有效負載。我將此稱為“錯誤請求”,但是當我嘗試通過curl 對正文發出 HEAD 請求時,我收到此錯誤。但是,Go 中不會發生日志記錄。package mainimport (    "fmt"    "log"    "net/http")func handler(w http.ResponseWriter, r *http.Request) {    log.Println(r.Method, r.URL)    _, _ = fmt.Fprintf(w, "Hello")}func main() {    http.HandleFunc("/", handler)    log.Fatal(http.ListenAndServe(":8080", nil))}如果我發送不帶正文的curl 請求,它將按預期工作并生成日志條目2019/11/28 10:58:59 HEAD /。$ curl -v -X HEAD  http://localhost:8080curl -i -X HEAD  http://localhost:8080Warning: Setting custom HTTP method to HEAD with -X/--request may not work theWarning: way you want. Consider using -I/--head instead.HTTP/1.1 200 OKDate: Thu, 28 Nov 2019 16:03:22 GMTContent-Length: 5Content-Type: text/plain; charset=utf-8但是,如果我發送帶有正文的curl 請求,則會收到“錯誤請求”狀態,但不會更新任何日志。$ curl -i -X HEAD  http://localhost:8080 -d '{}'Warning: Setting custom HTTP method to HEAD with -X/--request may not work theWarning: way you want. Consider using -I/--head instead.HTTP/1.1 400 Bad RequestContent-Type: text/plain; charset=utf-8Connection: close400 Bad Request我想捕獲此錯誤,以便可以發回我自己的自定義錯誤消息。我怎樣才能攔截這個?
查看完整描述

1 回答

?
POPMUISE

TA貢獻1765條經驗 獲得超5個贊

你不能。標準庫的 HTTP 服務器不為這種情況提供任何攔截點或回調。


在調用處理程序之前,無效請求將被“終止”。server.go您可以在,方法中看到這conn.serve()一點:


? ? w, err := c.readRequest(ctx)

? ? // ...

? ? if err != nil {

? ? ? ? switch {

? ? ? ? // ...

? ? ? ? default:

? ? ? ? ? ? publicErr := "400 Bad Request"

? ? ? ? ? ? if v, ok := err.(badRequestError); ok {

? ? ? ? ? ? ? ? publicErr = publicErr + ": " + string(v)

? ? ? ? ? ? }


? ? ? ? ? ? fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr)

? ? ? ? ? ? return

? ? ? ? }

? ? }

? ? // ...

? ? serverHandler{c.server}.ServeHTTP(w, w.req)

你不能。標準庫的 HTTP 服務器不為這種情況提供任何攔截點或回調。


在調用處理程序之前,無效請求將被“終止”。server.go您可以在,方法中看到這conn.serve()一點:


? ? w, err := c.readRequest(ctx)

? ? // ...

? ? if err != nil {

? ? ? ? switch {

? ? ? ? // ...

? ? ? ? default:

? ? ? ? ? ? publicErr := "400 Bad Request"

? ? ? ? ? ? if v, ok := err.(badRequestError); ok {

? ? ? ? ? ? ? ? publicErr = publicErr + ": " + string(v)

? ? ? ? ? ? }


? ? ? ? ? ? fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr)

? ? ? ? ? ? return

? ? ? ? }

? ? }

? ? // ...

? ? serverHandler{c.server}.ServeHTTP(w, w.req)

Go 的 HTTP 服務器為您提供了一個實現來處理來自使用/遵守HTTP 協議的客戶端的傳入請求。所有瀏覽器和著名的客戶端都遵循 HTTP 協議。提供完全可定制的服務器并不是實現的目標。



查看完整回答
反對 回復 2023-08-07
  • 1 回答
  • 0 關注
  • 181 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號