Search code examples
gorequestno-response

Golang: How to terminate/abort/cancel inbound http request without response?


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.


Solution

  • 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.