Skip to content

Commit fe40e5d

Browse files
authored
Hijack connection through http.ResponseController in http upgrader (#181)
1 parent 40c1550 commit fe40e5d

File tree

3 files changed

+38
-6
lines changed

3 files changed

+38
-6
lines changed

hijack_go119.go

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
//go:build !go1.20
2+
// +build !go1.20
3+
4+
package ws
5+
6+
import (
7+
"bufio"
8+
"net"
9+
"net/http"
10+
)
11+
12+
func hijack(w http.ResponseWriter) (net.Conn, *bufio.ReadWriter, error) {
13+
hj, ok := w.(http.Hijacker)
14+
if ok {
15+
return hj.Hijack()
16+
}
17+
return nil, nil, ErrNotHijacker
18+
}

hijack_go120.go

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
//go:build go1.20
2+
// +build go1.20
3+
4+
package ws
5+
6+
import (
7+
"bufio"
8+
"errors"
9+
"net"
10+
"net/http"
11+
)
12+
13+
func hijack(w http.ResponseWriter) (net.Conn, *bufio.ReadWriter, error) {
14+
conn, rw, err := http.NewResponseController(w).Hijack()
15+
if errors.Is(err, http.ErrNotSupported) {
16+
return nil, nil, ErrNotHijacker
17+
}
18+
return conn, rw, err
19+
}

server.go

+1-6
Original file line numberDiff line numberDiff line change
@@ -155,12 +155,7 @@ type HTTPUpgrader struct {
155155
func (u HTTPUpgrader) Upgrade(r *http.Request, w http.ResponseWriter) (conn net.Conn, rw *bufio.ReadWriter, hs Handshake, err error) {
156156
// Hijack connection first to get the ability to write rejection errors the
157157
// same way as in Upgrader.
158-
hj, ok := w.(http.Hijacker)
159-
if ok {
160-
conn, rw, err = hj.Hijack()
161-
} else {
162-
err = ErrNotHijacker
163-
}
158+
conn, rw, err = hijack(w)
164159
if err != nil {
165160
httpError(w, err.Error(), http.StatusInternalServerError)
166161
return conn, rw, hs, err

0 commit comments

Comments
 (0)