Golang:如何在没有响应的情况下终止/中止/取消传入的HTTP请求?

huangapple go评论79阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2016年4月8日 01:54:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/36483750.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定