【发布时间】: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/… 可能会有所帮助。