英文:
Golang: How to terminate/abort/cancel inbound http request without response?
问题
从服务器端,我需要终止/中止请求,而不向客户端返回任何响应,就像 nginx 的 444 错误 一样。
从客户端的角度来看,它应该表现为对等方重置连接。
英文:
From server side I need to terminate/abort request without any response to client like nginx's 444.
From client side it should look like connection reset by peer.
答案1
得分: 6
我花了几个小时,偶然发现了http.Hijacker
,它允许从http.ResponseWriter
获取网络连接:
h := func(w http.ResponseWriter, r *http.Request) {
if wr, ok := w.(http.Hijacker); ok {
conn, _, err := wr.Hijack()
if err != nil {
fmt.Fprint(w, err)
}
conn.Close()
}
}
在某些情况下,终止连接可能对节省CPU时间和出站流量很有用。
英文:
I've spent a couple hours and only accidentally find http.Hijacker
which allows to get access to net connection from http.ResponseWriter
:
h := func(w http.ResponseWriter, r *http.Request) {
if wr, ok := w.(http.Hijacker); ok {
conn, _, err := wr.Hijack()
if err != nil {
fmt.Fprint(w, err)
}
conn.Close()
}
}
Terminating connection may be useful in some cases for saving CPU time and outbound traffic.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论