是否有办法在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请求,那么我将获得Bad Request状态,但不会更新任何日志。
$ 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 protocol的客户端的传入请求。所有浏览器和著名的客户端都遵循HTTP协议。提供完全可定制的服务器不是实现的目标。