S
S
Seedor2020-07-07 17:10:52
go
Seedor, 2020-07-07 17:10:52

How to close connection from server side(net/http)?

Actually, there is a simple server.
The handler is called on the server side:

....
func testFuncHandler(w http.ResponseWriter, r *http.Request) {
  fmt.Fprint(w, "===data test_server_msg===")
}
....


How to close the connection forcibly after sending data to the client (connection of this particular client)?
(Don't offer general timeouts :) )

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
uvelichitel, 2020-07-07
@uvelichitel

For HTTP/1.x you can use http.Hijacker https://golang.org/pkg/net/http/#Hijacker to take control. More or less like this

func testFuncHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "===data test_server_msg===")
    hj, ok := w.(http.Hijacker) //Проверка протокола на возможность Hijack
    if !ok {
    http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError)
    return
    }
    conn, _, err  := hj.Hijack() //Вот здесь захват контроля
    if err != nil {
  http.Error(w, err.Error(), http.StatusInternalServerError)
  return
    }
    conn.Close()
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question