登录
首页 >  Golang >  Go问答

拦截错误的HTTP HEAD请求的方法

来源:stackoverflow

时间:2024-03-22 10:07:28 103浏览 收藏

珍惜时间,勤奋学习!今天给大家带来《拦截错误的HTTP HEAD请求的方法》,正文内容主要涉及到等等,如果你正在学习Golang,或者是对Golang有疑问,欢迎大家关注我!后面我会持续更新相关内容的,希望都能帮到正在学习的大家!

问题内容

有没有办法在 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.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 协议。提供完全可定制的服务器不是实现的目标。

今天关于《拦截错误的HTTP HEAD请求的方法》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>