为了账号安全,请及时绑定邮箱和手机立即绑定

如何拦截错误的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 关注
  • 83 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信