【问题标题】:How to intercept bad http HEAD request如何拦截错误的 http HEAD 请求
【发布时间】:2020-03-24 08:17:51
【问题描述】:

有没有办法在 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

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

【问题讨论】:

  • 检查 curl 给你的警告。 '-X HEAD' "指定自定义请求方法";而“-d”“在 POST 请求中发送指定的数据”。所以这意味着您正在请求两种不同的请求类型(POST 和 HEAD)。我不知道 curl 实际发送给应用程序的内容,但 400 表示它无效 - stackoverflow.com/questions/286982/… 可能会有所帮助。

标签: http go server


【解决方案1】:

你不能。标准库的 HTTP 服务器不提供任何拦截点或回调。

在调用您的处理程序之前,无效请求已被“杀死”。您可以在server.goconn.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 protocol 的客户端的传入请求。所有浏览器和著名的客户端都遵循 HTTP 协议。提供完全可定制的服务器并不是实现的目标。

【讨论】:

    猜你喜欢
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    • 2019-07-14
    • 1970-01-01
    相关资源
    最近更新 更多