如何拦截错误的 http HEAD 请求



有没有办法在Go HTTP服务器中拦截错误的HEAD请求? 这里的错误请求是发送带有 HEAD 请求的 JSON 有效负载。 我称之为错误请求,但是当我尝试通过 curl 对正文进行 HEAD 请求时,我收到此错误。 但是,Go 中不会发生日志记录。

package main
import (
"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:8080
curl -i -X HEAD  http://localhost:8080
Warning: Setting custom HTTP method to HEAD with -X/--request may not work the
Warning: way you want. Consider using -I/--head instead.
HTTP/1.1 200 OK
Date: Thu, 28 Nov 2019 16:03:22 GMT
Content-Length: 5
Content-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 the
Warning: way you want. Consider using -I/--head instead.
HTTP/1.1 400 Bad Request
Content-Type: text/plain; charset=utf-8
Connection: close
400 Bad Request

我想捕获此错误,以便我可以发送回自己的自定义错误消息。 我怎样才能拦截这个?

你不能。标准库的 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 协议。实现的目标不是提供完全可自定义的服务器。

最新更新