diff --git a/hijack_go119.go b/hijack_go119.go new file mode 100644 index 0000000..6ac556c --- /dev/null +++ b/hijack_go119.go @@ -0,0 +1,18 @@ +//go:build !go1.20 +// +build !go1.20 + +package ws + +import ( + "bufio" + "net" + "net/http" +) + +func hijack(w http.ResponseWriter) (net.Conn, *bufio.ReadWriter, error) { + hj, ok := w.(http.Hijacker) + if ok { + return hj.Hijack() + } + return nil, nil, ErrNotHijacker +} diff --git a/hijack_go120.go b/hijack_go120.go new file mode 100644 index 0000000..e67b439 --- /dev/null +++ b/hijack_go120.go @@ -0,0 +1,19 @@ +//go:build go1.20 +// +build go1.20 + +package ws + +import ( + "bufio" + "errors" + "net" + "net/http" +) + +func hijack(w http.ResponseWriter) (net.Conn, *bufio.ReadWriter, error) { + conn, rw, err := http.NewResponseController(w).Hijack() + if errors.Is(err, http.ErrNotSupported) { + return nil, nil, ErrNotHijacker + } + return conn, rw, err +} diff --git a/server.go b/server.go index f6cc8af..863bb22 100644 --- a/server.go +++ b/server.go @@ -155,12 +155,7 @@ type HTTPUpgrader struct { func (u HTTPUpgrader) Upgrade(r *http.Request, w http.ResponseWriter) (conn net.Conn, rw *bufio.ReadWriter, hs Handshake, err error) { // Hijack connection first to get the ability to write rejection errors the // same way as in Upgrader. - hj, ok := w.(http.Hijacker) - if ok { - conn, rw, err = hj.Hijack() - } else { - err = ErrNotHijacker - } + conn, rw, err = hijack(w) if err != nil { httpError(w, err.Error(), http.StatusInternalServerError) return conn, rw, hs, err